最近看到项目中有满屏的try catch,每个接口都做了 try/catch 处理,而且一旦需要调整,所有的接口都需要修改一遍,非常不利于代码的维护,然后就想着配置一下全局异常处理器。
全局异常处理
1.配置一下异常类
public class UserNotExitException extends Exception{
private static final long serialVersionUID = 1L;
private String errorCode;
public UserNotExitException(String errorCode) {
this(errorCode, "");
}
public UserNotExitException(String errorCode, String message) {
super("errorCode: " + errorCode + ", message: " + message);
this.errorCode = errorCode;
}
public String getErrorCode() {
return this.errorCode;
}
}
2.全局异常拦截器添加自定义异常类
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotExitException.class)
public ResultInfo handleValidationException(UserNotExitException e) {
return new ResultInfo(5000, e.getMessage());
}
@ExceptionHandler(DuplicateKeyException.class)
public ResultInfo handlerDuplicateKeyException(DuplicateKeyException e) {
return new ResultInfo(1000,e.getMessage());
}
}
3.controller测试
@RestController
@RequestMapping("user")
public class DemoController {
@GetMapping("/testException")
public Integer testException(Integer a,Integer b) throws UserNotExitException {
if(b==null){
throw new UserNotExitException("1000","失败");
}
return a+b;
}
@GetMapping("/getUser")
public boolean getUser() throws Exception {
throw new UserNotExitException("5000","请求用户失败");
}
4.返回值类
@Data
public class ResultInfo {
public final static String FAILED = "1001";
private Integer code;
private String message;
public ResultInfo(Integer code, String message) {
this.code = code;
this.message = message;
}
}
5.postman测试结果
6.项目结构