统一异常处理

日常开发中,我们一般都是自定义统一的异常类
自定义异常可以携带更多的信息。
项目开发中经常是很多人负责不同的模块,使用自定义异常可以统一了对外异常展示的方式。
自定义异常语义更加清晰明了,一看就知道是项目中手动抛出的异常。

自定义异常类, 所在包结构:

/**
 * 基础异常
 * @author spikeCong
 * @date 2023/2/28
 **/
public class BaseException extends RuntimeException{


    /**
     * 错误码
     */
    private String code;


    /**
     * 错误消息
     */
    private String defaultMessage;

    public BaseException() {
    }

    public BaseException(String code, String defaultMessage) {
        this.code = code;
        this.defaultMessage = defaultMessage;
    }

    public String getCode() {
        return code;
    }

    public String getDefaultMessage() {
        return defaultMessage;
    }
}

在controller 层,我们来使用这个自定义异常:

@RequestMapping("/queryUser")
public BaseResponse queryUser(User user){

    //模拟查询失败抛出异常
    throw new BaseException("500","测试异常类!");
}

这时我们可以借助注解@RestControllerAdvice,让代码更优雅。@RestControllerAdvice是一个应用于Controller层的切面注解,它一般配合@ExceptionHandler注解一起使用,作为项目的全局异常处理。示例代码如下:

/**
 * 全局异常处理器
 * @author spikeCong
 * @date 2023/2/28
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public BaseResponse baseExceptionHandler(BaseException e){
        return BaseResponse.fail(e.getDefaultMessage());
    }
}

我们有想要拦截的异常类型,比如想拦截BaseException类型,就新增一个方法,使用@ExceptionHandler注解修饰,并指定你想处理的异常类型,接着在方法内编写对该异常的操作逻辑,就完成了对该异常的全局处理!

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 基础异常
     * @param e
     * @return: com.msb.hjycommunity.common.core.domain.BaseResponse
     */
    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public BaseResponse baseExceptionHandler(BaseException e){
        
        return BaseResponse.fail(e.getDefaultMessage());
    }
}

测试

http://localhost:8888/hejiayun/user/queryUser

{
  "code": "500",
  "message": "测试异常类!",
  "data": null
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值