侧边栏壁纸
  • 累计撰写 79 篇文章
  • 累计创建 7 个标签
  • 累计收到 0 条评论

全局统一异常处理

水龙吟
2022-02-01 / 0 评论 / 0 点赞 / 153 阅读 / 896 字
温馨提示:
本文最后更新于 2022-02-02,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
@Slf4j
@Component //Spring容易自动管理
@RestControllerAdvice //在controller层添加通知。如果使用@ControllerAdvice,则方法上需要添加@ResponseBody
@RestControllerAdvice=@ControllerAdvice+@ResponseBody
public class UnifiedExceptionHandler {

    /**
     * 未定义异常
     */
    @ExceptionHandler(value = Exception.class) //当controller中抛出Exception,则捕获
    public R handleException(Exception e) {
        log.error(e.getMessage(), e);
        return R.error();
    }
}


/**
* 特定异常
*/
@ExceptionHandler(BadSqlGrammarException.class)
public R handleBadSqlGrammarException(BadSqlGrammarException e){
    log.error(e.getMessage(), e);
    return R.setResult(ResponseEnum.BAD_SQL_GRAMMAR_ERROR);
}

创建自定义异常类
@Data
@NoArgsConstructor
public class BusinessException extends RuntimeException {

//状态码
private Integer code;

//错误消息
private String message;

}

添加异常处理方法
/**

  • 自定义异常
    */
    @ExceptionHandler(BusinessException.class)
    public R handleBusinessException(BusinessException e){
    log.error(e.getMessage(), e);
    return R.error().message(e.getMessage()).code(e.getCode());
    }

0

评论区