Springboot全局异常处理GlobalExceptionHandler

Springboot的全局异常查是通过两个注解@ControllerAdvice和@ExceptionHandler来实现的。

只有代码出错或者throw出来的异常才会被捕捉处理,如果被catch的异常,就不会被捕捉,除非catch之后再throw异常。

@ControllerAdvice:增强型控制器,对于控制器的全局配置放在同一个位置,全局异常的注解,放在类上。

@ControllerAdvice默认只会处理controller层抛出的异常,如果需要处理service层的异常,需要定义一个自定义的MyException来继承RuntimeException类,然后@ExceptionHandler(MyException)即可。

@ExceptionHandler:指明需要处理的异常类型以及子类。注解放在方法上面。

例子:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler()
    public ResponseEntity exceptionHandle(Exception e){ // 处理方法参数的异常类型
        return null;//自己需要实现的异常处理
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity handle(BaseException e){
        return null; //自己需要实现的异常处理
    }

@ExceptionHandler(RuntimeException.class): 会先查看异常是否属于RuntimeException异常以及其子类,如果是的话,就用这个方法进行处理。

一个方法处理多个异常类的异常:@ExceptionHandler(value={RuntimeException.class,MyRuntimeException.class})

@ExceptionHandler():会根据方法参数的异常类型进行处理。

有多个@ExceptionHandler注解的方法时,会根据抛出异常类去寻找处理方法,如果没有,就往上找父类,直到找到为止。

 

 

 

 

Spring Boot 提供了一种简单的方式来配置全局异常处理,这样在整个应用中可以统一处理各种运行时错误。通常,你可以在Spring Boot项目的`application.properties`或`application.yml`文件中设置`spring-boot.bind-initializers`属性,将自定义的全局异常处理器初始化类路径下。 创建全局异常处理器的一般步骤如下: 1. 创建一个实现了`org.springframework.web.servlet.HandlerExceptionResolver`接口的类,比如`GlobalExceptionHandler`。这个类需要覆盖`resolveException()`方法,接收并处理`HttpServletRequest`、`HttpServletResponse`和`Throwable`作为参数。 ```java import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) public ResponseEntity<Object> handleAllExceptions(Exception ex) { // Log the exception logger.error("An unexpected error occurred", ex); // Prepare a response with an appropriate status code and message return new ResponseEntity<>(new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } private static class ErrorResponse { int code; String message; // Constructor and getters/setters... } } ``` 在这个例子中,如果应用程序遇到任何未处理的异常,它会返回一个包含错误码和消息的响应。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值