SpringBoot全局异常拦截与自定义错误页面实现过程解读

本文主要是介绍SpringBoot全局异常拦截与自定义错误页面实现过程解读,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《SpringBoot全局异常拦截与自定义错误页面实现过程解读》本文介绍了SpringBoot中全局异常拦截与自定义错误页面的实现方法,包括异常的分类、SpringBoot默认异常处理机制、全局异常拦...

一、引言

在开发基于Spring Boot的应用程序时,异常处理是一个至关重要的环节。合理的异常处理机制不仅可以提高系统的稳定性和可靠性,还能为用户提供友好的错误反馈。

本文将深入探讨Spring Boot中全局异常拦截与自定义错误页面的实现,旨在帮助技术人员掌握这一关键技能。

二、Spring Boot异常处理基础

2.1 异常的分类

Java中,异常分为受检查异常(Checked Exception)和非受检查异常(Unchecked Exception)。

受检查异常通常是程序在编译时就需要处理的异常,如IOException;非受检查异常一般是运行时异常,如NullPointerException、ArrayIndexOutOfBoundsException等。

2.2 Spring Boot默认异常处理机制

Spring Boot为我们提供了默认的异常处理机制。当应用程序抛出异常时,Spring Boot会根据异常类型返回相应的HTTP状态码和错误信息。例如,当发生404错误时,会返回一个包含错误信息的jsON响应。

下面是一个简单的Spring Boot应用示例:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @GetMapping("/test")
    public String test() {
        throw new RuntimeException("Test exception");
    }
}

当访问/test路径时,Spring Boot会返回一个包含错误信息的JSON响应。

三、全局异常拦截实现

3.1 自定义异常处理器

为了实现全局异常拦截,我们可以创建一个自定义的异常处理器类,使用@ControllerAdvice@ExceptionHandler注解。@ControllerAdvice注解用于定义全局异常处理器,@ExceptionHandler注解用于指定处理的异常类型。

以下是一个简单的全局异常处理器示例:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotatiyTMdwIMrUon.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException e) {
        return new ResponseEntity<>("Runtime exception occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

在上述代码中,GlobalExceptionHandler类使用@ControllerAdvice注解标记为全局异常处理器,handleRuntimeException方法使用@ExceptionHandler注解指定处理RuntimeException类型的异常。

3.2 处理不同类型的异常

除了处理RuntimeException,我们还可以处理其他类型的异常。

例如,处理NullPointerExceptionIllegalArgumentException

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<String> handleNullPointerException(NullPointerException e) {
        return new Responsehttp://www.chinasem.cnEntity<>("Null pointer exception occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(IllegyTMdWIMrUalArgumentException.class)
    public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException e) {
        return new ResponseEntity<>("Illegal argument exception occurred: " + e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}

3.3 自定义异常类

在实际开发中,我们可以创建自定义异常类,以便更好地管理和处理特定业务场景下的异常。

例如,创建一个自定义的业务异常类:

public class BusinessException extends RuntimeException {
    public BusinessException(String message) {
        super(message);
    }
}

然后在全局异常处理器中处理该自定义异常:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<String> handleBusinessException(BusinessException e) {
        return new ResponseEntity<>("Business exception occurred: " + e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}

四、自定义错误页面实现

4.1 基本原理

Spring Boot允许我们自定义错误页面,当发生特定的HTTP状态码错误时,会自动跳转到相应的错误页面。

我们可以在src/main/resources/templates目录下创建错误页面文件,文件名格式为error-{status}.html,其中{status}为HTTP状态码。

4.2 创建自定义错误页面

以下是一个简单的404错误页面示例(error-404.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>404 Not Found</title>
</head>
<body>
    <h1>404 Not Found</h1>
    <p>The requested resource was not found.</p>
</body>
</html>

同样,我们可以创建500错误页面(error-500.html):

<!DOCTYPE html>
<编程;html lang="en">
<head>
    <meta charset="UTF-8">
    <title>500 Internal Server Error</title>
</head>
<body>
    <h1>500 Internal Server Error</h1>
    <p>An unexpected error occurred on the server.</p>
</body>
</html>

4.3 配置错误页面

在Spring Boot中,默认情况下会自动查找src/main/resources/templates目录下的错误页面。如果需要自定义错误页面的位置,可以在application.propertiesapplication.yml中进行配置。

application.properties中配置:

server.error.path=/error
spring.mvc.view.prefix=/templates/
spring.mvc.view.suffix=.html

application.yml中配置:

server:
  error:
    path: /error
spring:
  mvc:
    view:
      prefix: /templates/
      suffix: .html

五、集成全局异常拦截与自定义错误页面

5.1 异常处理与错误页面结合

在全局异常处理器中,我们可以根据异常类型返回不同的HTTP状态码,从而跳转到相应的错误页面。例如:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Void> handleRuntimeException(RuntimeException e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Void> handleIllegalArgumentException(IllegalArgumentException e) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
}

当发生RuntimeException时,会返回500状态码,跳转到error-500.html页面;当发生IllegalArgumentException时,会返回400状态码,跳转到err编程or-400.html页面。

5.2 测试与验证

启动Spring Boot应用程序,访问不同的路径,触发不同类型的异常,验证全局异常拦截和自定义错误页面是否正常工作。

六、总结

通过本文的介绍,我们了解了Spring Boot中全局异常拦截与自定义错误页面的实现方法。

全局异常拦截可以帮助我们统一处理应用程序中的异常,提高代码的可维护性和系统的稳定性;自定义错误页面可以为用户提供更友好的错误反馈,提升用户体验。

在实际开发中,我们可以根据具体需求灵活运用这些技术,打造更加健壮和易用的Spring Boot应用程序。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持China编程(www.chinasem.cn)。

这篇关于SpringBoot全局异常拦截与自定义错误页面实现过程解读的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1156434

相关文章

springboot+redis实现订单过期(超时取消)功能的方法详解

《springboot+redis实现订单过期(超时取消)功能的方法详解》在SpringBoot中使用Redis实现订单过期(超时取消)功能,有多种成熟方案,本文为大家整理了几个详细方法,文中的示例代... 目录一、Redis键过期回调方案(推荐)1. 配置Redis监听器2. 监听键过期事件3. Redi

Spring Boot 处理带文件表单的方式汇总

《SpringBoot处理带文件表单的方式汇总》本文详细介绍了六种处理文件上传的方式,包括@RequestParam、@RequestPart、@ModelAttribute、@ModelAttr... 目录方式 1:@RequestParam接收文件后端代码前端代码特点方式 2:@RequestPart接

SpringBoot整合Zuul全过程

《SpringBoot整合Zuul全过程》Zuul网关是微服务架构中的重要组件,具备统一入口、鉴权校验、动态路由等功能,它通过配置文件进行灵活的路由和过滤器设置,支持Hystrix进行容错处理,还提供... 目录Zuul网关的作用Zuul网关的应用1、网关访问方式2、网关依赖注入3、网关启动器4、网关全局变

基于SpringBoot实现分布式锁的三种方法

《基于SpringBoot实现分布式锁的三种方法》这篇文章主要为大家详细介绍了基于SpringBoot实现分布式锁的三种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、基于Redis原生命令实现分布式锁1. 基础版Redis分布式锁2. 可重入锁实现二、使用Redisso

SpringBoo WebFlux+MongoDB实现非阻塞API过程

《SpringBooWebFlux+MongoDB实现非阻塞API过程》本文介绍了如何使用SpringBootWebFlux和MongoDB实现非阻塞API,通过响应式编程提高系统的吞吐量和响应性能... 目录一、引言二、响应式编程基础2.1 响应式编程概念2.2 响应式编程的优势2.3 响应式编程相关技术

SpringBoot的全局异常拦截实践过程

《SpringBoot的全局异常拦截实践过程》SpringBoot中使用@ControllerAdvice和@ExceptionHandler实现全局异常拦截,@RestControllerAdvic... 目录@RestControllerAdvice@ResponseStatus(...)@Except

Springboot配置文件相关语法及读取方式详解

《Springboot配置文件相关语法及读取方式详解》本文主要介绍了SpringBoot中的两种配置文件形式,即.properties文件和.yml/.yaml文件,详细讲解了这两种文件的语法和读取方... 目录配置文件的形式语法1、key-value形式2、数组形式读取方式1、通过@value注解2、通过

Java 接口定义变量的示例代码

《Java接口定义变量的示例代码》文章介绍了Java接口中的变量和方法,接口中的变量必须是publicstaticfinal的,用于定义常量,而方法默认是publicabstract的,必须由实现类... 在 Java 中,接口是一种抽象类型,用于定义类必须实现的方法。接口可以包含常量和方法,但不能包含实例

JAVA Calendar设置上个月时,日期不存在或错误提示问题及解决

《JAVACalendar设置上个月时,日期不存在或错误提示问题及解决》在使用Java的Calendar类设置上个月的日期时,如果遇到不存在的日期(如4月31日),默认会自动调整到下个月的相应日期(... 目录Java Calendar设置上个月时,日期不存在或错误提示java进行日期计算时如果出现不存在的

Mybatis对MySQL if 函数的不支持问题解读

《Mybatis对MySQLif函数的不支持问题解读》接手项目后,为了实现多租户功能,引入了Mybatis-plus,发现之前运行正常的SQL语句报错,原因是Mybatis不支持MySQL的if函... 目录MyBATis对mysql if 函数的不支持问题描述经过查询网上搜索资料找到原因解决方案总结Myb