Spring Boot统一异常处理

在系统设计中,我们通常需要将自定义的异常以自定义的接口规范返回给客户端,以便进行统一的异常处理。

实现方式之ControllerAdvice

其中常用的一种方式是使用@RestControllerAdvice来实现,代码如下:

/**
 * 自定义的异常
 */
@Value
public class BizException extends RuntimeException {
    private Integer errCode;
    private String errMsg;
}

/**
 * 异常处理
 */
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyExceptionHandler {
    @ExceptionHandler({BizException.class})
    public Map<String, Object> handleClientException(BizException e) {
        Map<String, Object> result = new HashMap<String, Object>(2);
        result.put("errCode", result.getErrCode());
        result.put("errMsg", result.getErrMsg());
        return result;
    }
}

实现方式之BasicErrorController

上述定义的ControllerAdvice能够拦截并处理controller中抛出的异常,但是controller之外的则无法处理,但是可以通过修改Spring Boot中默认的异常处理BasicErrorController来实现。

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class MyErrorController extends BasicErrorController {

    public MyErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
        super(errorAttributes, serverProperties.getError());
    }

    @Override
    protected HttpStatus getStatus(HttpServletRequest request) {
        // 修改HTTP响应码
        return HttpStatus.OK;
    }

    @Override
    protected Map<String, Object> getErrorAttributes(HttpServletRequest request, ErrorAttributeOptions options) {
        // 修改返回的Body内容
        Map<String, Object> errorAttributes = new LinkedHashMap<>();
        errorAttributes.put("success", false);
        errorAttributes.put("code", i);
        errorAttributes.put("message", s);
        return errorAttributes;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值