Springboot统一异常处理

Springboot统一异常处理

本文是基于SpringBoot 2.0.4.release环境,学习和使用通用统一异常处理:


一、统一异常处理

(1)配置异常处理通知类

  • CommonExceptionHandler.java
@ControllerAdvice
public class CommonExceptionHandler {

    @ExceptionHandler(LyException.class)
    public ResponseEntity<ExceptionResult> handleException(LyException e){
        ExceptionEnum exceptionEnum = e.getExceptionEnum();
        return ResponseEntity.status(exceptionEnum.getHttpStatus()).body(new ExceptionResult(e.getExceptionEnum()));
    }
}

(2)配置异常枚举类

  • ExceptionEnum.java
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum ExceptionEnum {
    USERNAME_CANNOT_BE_NULL(HttpStatus.BAD_REQUEST.value(), "用户名不能为空"),
    PASSWORD_CANNOT_BE_NULL(HttpStatus.BAD_REQUEST.value(), "密码不能为空"),
    PASSWORD_BE_INCORRECT(HttpStatus.BAD_REQUEST.value(), "密码不正确");

    private int httpStatus;
    private String msg;
}

(3)配置异常类

  • LyException.java
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class LyException extends RuntimeException {
    private ExceptionEnum exceptionEnum;
}

(4)配置异常结果类

  • ExceptionResult.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExceptionResult {
    private int status;
    private String message;
    private Long timestamp;

    public ExceptionResult(ExceptionEnum em){
        this.status = em.getHttpStatus();
        this.message = em.getMsg();
        this.timestamp = System.currentTimeMillis();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值