代码编织梦想

创建全局统一异常类

@RestControllerAdvice

@Slf4j
@RestControllerAdvice
public class UninfiedExceptionHandler {

    @ExceptionHandler
    public JSONResult exceptionHandler(Throwable throwable) {
      log.info("统一异常,{}",throwable.getMessage());
      throwable.printStackTrace();
      return JSONResult.error("系统异常,我们正在救援猴子");
    }

    @ExceptionHandler(GlobalException.class)
    public JSONResult exceptionHandler(GlobalException e) {
        log.info("自定义异常,{}",e.getMessage());
        e.printStackTrace();
        return JSONResult.error(e);
    }
}

用我们准备的接口测试一下

64e36df62ad94e8aa2830bfecccb215e.png
ac9e1c8e76a245ca8ea798579995d91b.png
6cdcd0045e5e4f28af801ac5b5151a15.png

没有问题,去救援猴子了

那这时我们自定义的异常向抛给用户又该如何处理呢

我们重新写一个接口,测试

a3b48d859f0488dcaedc6c74ac4c0501.gif
aa778b3ee3e1d4bf1805fec26c21eaa9.gif

依旧抛出的是全局异常,如果我们要给用户返回其他异常怎么办呢

自定义异常

在创建一个我们自己的全局异常,即自定义全局异常

小伙伴们注意,下面的code字段时我自己加上去去的,直接继承RuntimeException是没有这个字段的

只与构造方法,让id自动生成就可以了,不用自己写哦

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class GlobalException extends RuntimeException {
    private String code;


    public GlobalException(String message, String code) {
        super(message);
        this.code = code;
    }

    public GlobalException(String message, Throwable cause, String code) {
        super(message, cause);
        this.code = code;
    }

    public GlobalException(Throwable cause, String code) {
        super(cause);
        this.code = code;
    }

    public GlobalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, String code) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.code = code;
    }
}

在我们之前的统一异常类UninfiedExceptionHandler 中在添加一个方法,即把我们的自定义全局异常加进去

import com.qyf.dto.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class UninfiedExceptionHandler {

    @ExceptionHandler
    public JSONResult exceptionHandler(Throwable throwable) {
      log.info("统一异常,{}",throwable.getMessage());
      throwable.printStackTrace();
      return JSONResult.error("系统异常,我们正在救援猴子");
    }

    @ExceptionHandler(GlobalException.class)
    public JSONResult exceptionHandler(GlobalException e) {
        log.info("自定义异常,{}",e.getMessage());
        e.printStackTrace();
        return JSONResult.error(e);
    }
}

来看看结果

e4ab19fd885d31b35bf1d97c5012731e.gif
9945c87dadd4a12fbf6d30b34b5c8b5e.gif

这个时候,想给用户抛什么异常可以随便写了

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/m0_48660016/article/details/129513299