一、概念:
1、介绍:
@ControllerAdvice注解是Spring框架中的一个注解,用于定义全局的控制器增强(Controller Advice)。它可以用于统一处理异常、全局数据绑定、全局数据预处理等。
2、作用:
@ControllerAdvice的作用包括:
统一异常处理:@ControllerAdvice可以捕获应用程序中抛出的异常,并对它们进行统一的处理。可以定义多个@ExceptionHandler方法,每个方法处理不同类型的异常。
全局数据绑定:@ControllerAdvice可以定义@ModelAttribute方法,用于将数据绑定到所有或指定类型的模型中,以便在多个控制器中共享。
全局数据预处理:@ControllerAdvice可以定义@InitBinder方法,用于对请求参数进行全局的预处理,例如数据格式转换、验证等。
二、自定义全局统一异常处理
在我们编写的项目中往往一不小心就会出现BUG,导致程序发生异常,使接口得不到对应的返回值,所以我们可以使用 @ControllerAdvice 注解加上 @ExceptionHandler 对全局异常进行捕获,做统一异常处理,即使程序发生异常前端也可以正常接收到数据,并且可以通过判断返回信息进行处理。
1、统一异常处理
@ControllerAdvice
@ResponseBody
@Slf4j
public class MyGlobalExceptionHandler {
/**
* runtime
* @param exception
* @return
*/
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseResult runtimeException(RuntimeException exception){
String message = exception.getMessage();
log.error(message);
return ResponseResult.fail(500,message);
}
}
我们编写全局异常统一处理类,使用 @ExceptionHandler 对全局运行时异常进行捕获,当程序发生运行时异常时没有进行处理,而是抛出就会被捕获到,此时我们可以提取异常信息,使用@ResponseStatus 设置相应状态码 ,并使用 @ResponseBody 进行处理,转换成json数据返回给前端。
2、自定义异常类
@Data
public class ErrorException extends RuntimeException{
private String msg;
public ErrorException(){}
public ErrorException(String msg){
super(msg);
this.msg =msg;
}
public static void cast(String msg){
throw new ErrorException(msg);
}
}
自定义的异常类继承于RuntimeException,并提供msg异常信息属性,我们可以再可能发生异常处调用cast()方法,抛出我们自定义的异常。
3、处理自定义异常
@ControllerAdvice
@ResponseBody
@Slf4j
public class MyGlobalExceptionHandler {
/**
* runtime
* @param exception
* @return
*/
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseResult runtimeException(RuntimeException exception){
String message = exception.getMessage();
log.error(message);
return ResponseResult.fail(500,message);
}
/**
* 自定义异常
* @param error
* @return
*/
@ExceptionHandler(ErrorException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseResult error(Error error){
String message = error.getMessage();
log.error(message);
return ResponseResult.fail(520,message);
}
}
在统一异常处理上添加对自定义异常的捕获,这样就可以优雅的处理异常了。