6. 自定义异常 & 全局异常处理 & 测试异常处理

目录

1. 自定义异常

2. 全局异常处理

3. 测试异常处理


1. 自定义异常

创建⼀个异常类,加入状态码与状态描述属性。
凡是业务代码中出现的可预期的异常,统一抛出 ApplicationException
public class ApplicationException extends RuntimeException{

    // 用来描述具体的异常信息
    protected AppResult errorResult;

    public AppResult getErrorResult() {
        return errorResult;
    }

    public ApplicationException(AppResult errorResult) {
        super(errorResult.getMessage());
        this.errorResult = errorResult;
    }

    public ApplicationException(String message) {
        super(message);
    }

    public ApplicationException(String message, Throwable cause, AppResult errorResult) {
        super(message, cause);
    }

    public ApplicationException(Throwable cause, AppResult errorResult) {
        super(cause);
    }
}

2. 全局异常处理

使用 @ControllerAdvice + @ExceptionHandler 注解实现统⼀异常处理,@ControllerAdvice 表示控制器通知类。
//添加注解
@Slf4j  // 日志
@ControllerAdvice
public class GlobalExceptionHandler {
    // 以 JSON 的形式返回 body 中的数据
    @ResponseBody
    // 指定要处理的异常
    @ExceptionHandler(ApplicationException.class)
    public AppResult handleApplication(ApplicationException exception){
        // 打印异常信息,上线生产之前要删除这个打印方式
        exception.printStackTrace();
        // 打印日志
        log.info(exception.getMessage());
        // 判断自定义的异常信息是否为空
        if(exception.getErrorResult() != null){
            // 返回异常类中记录的状态
            return exception.getErrorResult();
        }
        // 根据异常信息,封装 AppResult
        return AppResult.failed(exception.getMessage());
    }
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult handeleException(Exception e){
        // 打印异常信息,上线生产之前要删除这个打印方式
        e.printStackTrace();
        // 打印日志
        log.info(e.getMessage());
        // 判断自定义的异常信息是否为空
        if(e.getMessage() != null){
            // 默认异常信息
            return AppResult.failed(ResultCode.ERROR_SERVICES.getMessage());
        }
        // 根据异常信息,封装 AppResult
        return AppResult.failed(e.getMessage());
    }
}

3. 测试异常处理

在TestController中添加如下方法:
@Slf4j //日志
@RestController //表示在 Body 中返回数据
@RequestMapping("/test") // 一级映射路径
public class TestController {

    @GetMapping("/hello") // 二级映射路径
    public String hello() {
        return "Hello, Spring Boot...";
    }

    @GetMapping("/exception")
    public AppResult testException() throws Exception{
        throw new Exception("这是一个 Exception...");
    }

    @GetMapping("/applicationException")
    public AppResult testApplicationException(){
        throw new ApplicationException("这是一个 ApplicationException...");
    }
}

可以看到异常处理的相关代码测试成功,可以正常运行。 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值