0%

SpringBoot项目实战之@ControllerAdvice+@ExceptionHandler实现全局异常统一处理

注解说明

@ControllerAdvice(或@RestControllerAdvice)

本质上是Component,会被当做组件扫描。一般配合@InitBinder、@ModelAttribute、@ExceptionHandler来使用,实现以下三个方面的功能:

1、全局数据预处理
2、全局数据绑定
3、全局异常处理
今天我们主要介绍第三种功能,在平时的项目中使用的比较广泛,可以实现在后台业务处理时抛出自定义错误,传回前台,此时前台就可以友好的将错误提示给用户。

源码

@ExceptionHandler(”异常类名”)

被此注解修饰的方法会在系统抛出在括号中定义的异常时自动触发。
如下面的用例中,当系统抛出自定义异常MyException时,会自动触发handlerError()方法,将错误码与错误信息封装好返回给前台。

代码示例

自定义异常基类

继承自RuntimeException

1
2
3
4
5
6
7
8
9
10
11
12
@Data
public class MyException extends RuntimeException {
private String errorMsg;

private int errorCode;

public MyException(int errorCode,String errorMsg){
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}

}

统一异常处理类

1
2
3
4
5
6
7
8
9
10
11
12
@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(MyException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResult handlerError(MyException ex) {
ErrorResult errorResult = new ErrorResult();
errorResult.setErrorCode(ex.getErrorCode());
errorResult.setErrorMsg(ex.getErrorMsg());
return errorResult;
}
}

封装的返回实体类

1
2
3
4
5
6
7
8
@Data
@ToString
public class ErrorResult {

private int errorCode;

private String errorMsg;
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
@RestController("/")
public class TestController {

@RequestMapping(method = RequestMethod.GET, path = {"/test"})
public ResponseEntity<?> test(@RequestParam String id) {
if (StringUtils.isEmpty(id)) {
throw new MyException(500, "id不能为空");
}
return new ResponseEntity<>(null, HttpStatus.OK);
}

}

测试结果

测试结果

项目结构

在这里插入图片描述