项目全局异常怎么处理

一、使用指定注解来拦截异常

@ControllerAdvice()

     拦截拥有指定注解的类。

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

}

@ControllerAdvice(annotations = {RestController.class, Controller.class})  

即拦截被注解@RestController和@Controller标注类中的异常,并交由GlobalExceptionHandler该类来处理。

@ExceptionHandler

     拦截到的指定异常处理的方法,括号内添加报错的异常信息的类

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        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("未知错误");
    }
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)

当抛出数据库中执行违反完整性约束异常时,Spring MVC框架会自动将该异常转发给当前的@ExceptionHandler方法进行处理,并将返回值作为HTTP响应返回给客户端。

二、自定义本地异常类

/**
 * 自定义业务异常类,直接继承运行时异常即可
 */
public class CustomException extends RuntimeException {
    public CustomException(String message){
        super(message);
    }
}

三、将本地自定义异常交由全局异常托管 (完整代码如下)

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

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        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("未知错误");
    }

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

        return R.error(ex.getMessage());
    }

}

posted @   南方的猫  阅读(15)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示