学习Spring Boot:(九)统一异常处理

前言

开发的时候,每个controller的接口都需要进行捕捉异常的处理,以前有的是用切面做的,但是SpringMVC中就自带了@ControllerAdvice ,用来定义统一异常处理类,在 SpringBoot 中额外增加了 @RestControllerAdvice

使用

创建全局异常处理类

通过使用 @ControllerAdvice 或者 @RestControllerAdvice 定义统一的异常处理类。

在方法的注解上加上 @ExceptionHandler 用来指定这个方法用来处理哪种异常类型,然后处理完异常,将相关的结果返回。

@RestControllerAdvice
public class ExceptionHandler {
    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);

    /**
     * 处理系统自定义的异常
     *
     * @param e 异常
     * @return 状态码和错误信息
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(KCException.class)
    public ResponseEntity<String> handleKCException(KCException e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseEntity.status(e.getCode()).body(e.getMessage());
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(DuplicateKeyException.class)
    public ResponseEntity<String> handleDuplicateKeyException(DuplicateKeyException e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.CONFLICT).body("数据库中已存在该记录");
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(AuthorizationException.class)
    public ResponseEntity<String> handleAuthorizationException(AuthorizationException e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("没有权限,请联系管理员授权");
    }

    /**
     * 处理异常
     *
     * @param e 异常
     * @return 状态码
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

测试

我在 controller 写了一个新增的方法,由于我的数据库中设置了 username 字段唯一索引,所以相同的值添加第二次的时候,肯定会抛出上面方法中的第二个异常 DuplicateKeyException

@PostMapping()
    public ResponseEntity insert(@RequestBody SysUserEntity user) {
        sysUserService.save(user);
        return ResponseEntity.status(CREATED).build();
    }

第一次新增的时候:
image

第二次新增的时候返回异常信息:
image

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值