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();
    }
}

你可能感兴趣的:(Java)