SpringBoot里全局 非expcetion异常处理 非WebFlex

21 篇文章 1 订阅
9 篇文章 0 订阅

SpringBoot异常处理机制
在SpringBoot中,常用的异常处理有两种,一种是BasicErrorController,另一种是@ControllerAdvice,BasicErrorController用于处理非Controller抛出的异常,而@ControllerAdvice用于处理Controller抛出的异常,对于非Controller抛出的异常它是不会管的。

但是,如果是Controller层调用Service层,从Service层抛出,依然会抛到Controller,所以还是会调用@ControllerAdvice进行处理

以BasicErrorController为例,我们如何去创建一个自定的异常处理类呐?

BasicErrorController创建及配置
创建代码类并继承BasicErrorController
代码类

public class MyErrorController extends BasicErrorController {


    public MyErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }

    @SneakyThrows
    @Override
    protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {

        Map<String, Object> attributes = super.getErrorAttributes(request, includeStackTrace);
        attributes.remove("timestamp");
        attributes.remove("status");
        attributes.remove("error");
        attributes.remove("exception");
        attributes.remove("path");
        String messageCode = (String) attributes.get("message");
        ErrorEnum errorEnum = null;
        try {
            errorEnum = ErrorEnum.getEnumByCode(messageCode);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (errorEnum==null){

            attributes.put("type","0");
            attributes.put("message","枚举类异常");
            return attributes;

        }

        attributes.put("errorControllerType","basicErrorController");
        attributes.put("type",errorEnum.getCode());
        attributes.put("message",errorEnum.getMessage());
        return attributes;
    }
}

配置MyErrorController
首先我们知道SpringBoot的大部分配置可以在ErrorMvcAutoConfiguration中找到,打开ErrorMvcAutoConfiguration源码,可以看到ErrorMvcAutoConfiguration中对

BasicErrorController进行了配置,为此在继承BasicErrorController后也应当对继承类进行配置。

ErrorMvcAutoConfiguration中的BasicErrorController配置如下

@Bean
	@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
	public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
		return new BasicErrorController(errorAttributes, this.serverProperties.getError(), this.errorViewResolvers);
	}

我们知道,需要ErrorAttributes errorAttributes, ErrorProperties errorProperties, List errorViewResolvers,三个参数,而ErrorMvcAutoConfiguration源码中配置中只有ErrorAttributes errorAttributes一个参数,而另外一个参数则在new BasicErrorController(errorAttributes, this.serverProperties.getError(), this.errorViewResolvers) 中找到,即his.serverProperties.getError(),最后一个参数点两下,可以知道在ErrorMvcAutoConfiguration构造函数中,即this.errorViewResolvers = errorViewResolvers.orderedStream().collect(Collectors.toList());


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

    public CustomErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties,
                                 ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) {
        super(errorAttributes, serverProperties.getError(),
                (List)errorViewResolversProvider.orderedStream().collect(Collectors.toList()));
    }

    @RequestMapping
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = super.getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity(status);
        } else {
            Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
            body.put("resp_msg", body.get("message"));
            body.put("resp_code", body.get("status"));
            body.remove("status");
            body.remove("message");
            return new ResponseEntity(body, status);
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

inthirties

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值