Java自定义异常和全局异常处理

1、自定义异常:自定义异常类 BusinessException extends RuntimeException:RuntimeException是 Java 提供的一个运行时异常类。

public class BusinessException extends RuntimeException {
 
    private int code;
    //使用枚举构造
    public BusinessException(HttpCodeEnum httpCodeEnum){
        super(httpCodeEnum.getMsg());
        this.code=httpCodeEnum.getCode();
    }
    //使用自定义消息体
    public BusinessException(HttpCodeEnum httpCodeEnum, String msg){
        super(msg);
        this.code=httpCodeEnum.getCode();
    }
    //根据异常构造
    public BusinessException(HttpCodeEnum httpCodeEnum, Throwable msg){
        super(msg);
        this.code=httpCodeEnum.getCode();
    }
}

异常枚举类:

public enum HttpCodeEnum {
    SUCCESS(200, "操作成功"),
    NEED_LOGIN(401, "需要登录后操作"),
    NO_OPERATOR_AUTH(403, "无权限操作"),
    SYSTEM_ERROR(500, "出现错误")
    int code;
    String msg;
    HttpCodeEnum(int code, String errorMessage) {
        this.code = code;
        this.msg = errorMessage;
    }
    public int getCode() {
        return code;
    }
    public String getMsg() {
        return msg;
    }
}

2、自定义全局异常拦截:使用 @RestControllerAdvice 注解和 @ExceptionHandler 注解来实现全局异常拦截

@ExceptionHandler()用于匹配程序发生的异常 然后做出对应的响应
@ResponseStatus(HttpStatus.OK) 表示返回的http状态码,例如如果想要程序抛出异常时候 http状态码还是200 就可以使用HttpStatus.OK,响应体的实际异常状态码由自定义异常code决定,两者并不一致。

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 参数非法异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Wrapper<?> illegalArgumentException(IllegalArgumentException e) {
        log.error("参数非法异常={}", e.getMessage(), e);
        return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
    }

    /**
     * 业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Wrapper<?> businessException(BusinessException e) {
        log.error("业务异常={}", e.getMessage(), e);
        return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
    }

    /**
     * 主鍵冲突异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Wrapper<?> duplicateKeyException(DuplicateKeyException e) {
        log.error("主鍵冲突异常={}", e.getMessage(), e);
        return WrapMapper.wrap(Wrapper.ERROR_CODE, "请稍后再试", WrapMapper.wrap(Wrapper.ERROR_CODE, "请稍后再试"));
    }

/** * 全局异常 * * @param e * @return */ @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.OK) @ResponseBody public Wrapper<?> exception(Exception e) { log.error("保存全局异常信息 ex={}", e.getMessage(), e); return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage()); } }

 

posted @ 2024-03-07 10:47  山阴路的秋天  阅读(109)  评论(0编辑  收藏  举报