目录
我们需要对程序中可能出现的异常进行捕获,通常有两种处理方式:
- 使用 try...catch 直接进行异常捕获,但是这种方式太繁琐了,难不成我有一个异常我就要写一次try...catch吗?虽然可以解决,但是存在弊端代码冗余,不通用。
- 使用异常处理器进行全局异常捕获,采用这种方式来实现,我们只需要在项目中定义一个通用的全局异常处理器,就可以解决本项目的所有异常。
在项目中自定义一个全局异常处理器,在异常处理器上加上注解 @ControllerAdvice,可以通过属性annotations指定拦截哪一类的Controller方法。

创建好全局异常处理器后,我们就可以去编写异常处理方法。
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.bind.annotation.RestController;
- import java.sql.SQLIntegrityConstraintViolationException;
-
- /**
- * 全局异常处理
- */
- @ControllerAdvice(annotations = {RestController.class, Controller.class})
- @ResponseBody
- @Slf4j
- public class GlobalExceptionHandler {
-
- /**
- * 异常处理方法 @ExceptionHandler 来指定拦截的是那一类型的异常。
- * @return
- */
- @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
- public R
exceptionHandler(SQLIntegrityConstraintViolationException ex){ - // 打印异常信息 例如 : Duplicate entry '666' for key 'idx_username'
- log.error(ex.getMessage());
- // 判断异常信息是否包括
- if(ex.getMessage().contains("Duplicate entry")){
- // 异常信息有空格,所以我们可以通过空格进行截取 获得一个数组
- String[] split = ex.getMessage().split(" ");
- String msg = split[2] + "已存在";
- // 返回异常处理信息
- return R.error(msg);
- }
- return R.error("未知错误");
- }
- }
上述的全局异常处理器上使用了的两个注解 @ControllerAdvice , @ResponseBody , 他们的作用分别为:
- @ControllerAdvice : 指定拦截那些类型的控制器;
- @ResponseBody: 将方法的返回值 R 对象转换为json格式的数据, 响应给页面;
上述使用的两个注解, 也可以合并成为一个注解 @RestControllerAdvice