Spring全局异常处理器

创建一个新类

添加@RestControllerAdvice注解,该注解用于定义全局异常处理类

@RestControllerAdvice //@RestControllerAdvice = @ControllerAdvice + @ResponseBody

使用@ExceptionHandler注解定义异常处理方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RestControllerAdvice //@RestControllerAdvice = @ControllerAdvice + @ResponseBody
public class GlobalExceptionHandler {

/**
* 这个注解是指定处理那些异常
* @param ex
* @return
*/
@ExceptionHandler(Exception.class)
public Result ex(Exception ex){
ex.printStackTrace();
// 如果抛出的异常有错误信息,直接返回给用户,否则返回一个默认的错误信息
return Result.error(StringUtils.hasLength(ex.getMessage()) ? ex.getMessage() : "对不起,操作失败,请联系管理员");
}
}