全局异常的使用(项目必备)

SpringBoot中,@ControllerAdvice 即可开启全局异常处理,使用该注解表示开启了全局异常的捕获,我们只需在自定义一个方法使用@ExceptionHandler注解然后定义捕获异常的类型即可对这些捕获的异常进行统一的处理。

1、@ControllerAdvice的使用:

 annotations:获取带有注解的类

RestController.class:带有@RestController注解的类

Controller.class:带有@Controller注解的类

2、@ExceptionHandler使用:异常处理方法

如果为空,将默认为方法参数列表中列出的任何异常。

/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * @param ex
     * @return
     */
    //传入SQLIntegrityConstraintViolationException.class异常类
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

        //contains() 方法用于判断字符串中是否包含指定的字符或字符串。
        if(ex.getMessage().contains("Duplicate entry")){
            //split(" ")去除空格
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }

        return R.error("未知错误");
    }
}


版权声明:本文为A1916403680原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。