srping boot 统一异常处理

参考:https://blog.csdn.net/liaodehong/article/details/76922710

可是有些请求不存在,404的话,根本进不到controller这一层,所以这类异常也捕获不了。

默认spring boot 返回的是:

{"timestamp":"2018-09-03T06:09:05.896+0000","status":404,"error":"Not Found","message":"No message available","path":"/xxxx/xxxxx.do"}

类似的json,不是我们想要封装的格式。

参考:https://blog.csdn.net/kenight/article/details/77371374

这篇是原理,可以看官方的网站

Spring boot 处理 error 的基本流程:

Controller -> 发生错误 -> BasicErrorController -> 根据 @RequestMapping(produces) 判断调用 errorHtml 或者 error 方法

然后:

errorHtml -> getErrorAttributes -> ErrorViewResolver -> 错误显示页面

error -> getErrorAttributes -> @ResponseBody (直接返回JSON)

如果想要定制一些东西,按照官方文档的建议可以:

1.继承 BasicErrorController  扩展处理一个新的 content type

2.自定义 ErrorAttributes 获得自己想要的结果集

3.实现 ErrorViewResolver 接口,自定义错误显示视图

 

 

1.捕获异常:

使用 @ControllerAdvice 与 @ExceptionHandler 捕获异常并处理(返回自定义json对象或是页面视图,将替代 ErrorAttributes、ErrorViewResolver)

注意:如 404 等是通过 Servlet (DispatcherServlet.noHandlerFound) 的处理并返回 response ( response.sendError) ,并未到达 Controller 层,所以并不能捕获到。

参考:https://segmentfault.com/a/1190000008443705

 

第一种方式 参考:https://blog.csdn.net/u013086392/article/details/78261751

@Configuration public class WebMvcConfigurer extends WebMvcConfigurerAdapter

public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { exceptionResolvers.add(new HandlerExceptionResolver() {

这种好像不美观。

第二种  可以,不过404 等错误捕捉不到

RestControllerAdvice
@ExceptionHandler (value = Exception.class)
public Object handle(HttpServletRequest request,
                     HttpServletResponse response, Exception e) {

 

第三种方式  不过这种方式 没办法获取到 异常对象 ,只是封装好的 e.printStackTrace();

@RestController
public class CustomerErrorController extends BasicErrorController
@RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {

 

第四种方式,重写dispatchServlet 在里面写处理exception的办法。异常中处理返回页面有点怪怪的。算了。

protected void service(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
   try {

      super.service(request, response);
   } catch (Exception e) {
      throw  e;
      //handleException(request, response, e);
   }
}

最后采用,第二种方式加第三种方式,第二种处理非404 等错误的情况,第三种处理 404错误的情况。第二种处理了的,不会进入到第三种里面。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值