Spring Boot - 全局异常处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fangmenghao/article/details/78986165

Spring Boot 全局异常处理

0x01 问题场景

在使用spring boot开发的时候好奇为什么网页访问返回页面而ajax访问返回json数据,以及如何处理异常

为什么使用@ExceptionHandler无法处理404

0x02 前置知识

了解servlet中处理错误的方式

spring mvc和spring boot异常捕获只是在请求过程中捕获异常,意味着只捕获进入Controller层的异常,其他异常会抛给服务器,所以有时候会出现一些tomcat的页面,而在spring boot中,因为实现了内置服务器,并重写了一个方法来处理异常。

spring boot有一个BasicErrorController用来兜底的,在ErrorMvcAutoConfiguration中配置了错误重定向到/error,该Controller实现了ErrorController接口,自动配置只有在没有发现实现了该接口的类时,就会自动加载BasicErrorController。

而返回结果是因为ViewResolver,有一个实现类会根据content-type返回不同的

0x03 解决思路

当开发API模块的使用,使用@ControllerAdvice配合@ExceptionHandler可以解决基本问题,同时为了捕获404等错误,还需要在application.yml中配置

spring:
    mvc:
        throw-exception-if-no-handler-found: true
    resources:
        add-mappings: false

这两个配置指定了要捕获请求未找到等异常,同时因为是API所以不需要有资源映射

当开发后台模块的时候,因为有ajax请求也有页面请求。方式是继承BasicErrorController即可

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

    public MyBasicExtendsController(){
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        return new ResponseEntity(HttpStatus.BAD_REQUEST);
    }

    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        return super.errorHtml(request, response);
    }
}

然后重写2个方法即可,还有一些需要定制的参数也可以自己注入。然后只要实现一个error.html的页面即可。

0xFF 参考资料

https://www.cnblogs.com/xinzhao/p/4934247.html?utm_source=tuicool&utm_medium=referral

https://www.cnblogs.com/xinzhao/p/4902295.html?utm_source=tuicool&utm_medium=referral

https://segmentfault.com/a/1190000010060540

https://segmentfault.com/a/1190000006749441

猜你喜欢

转载自blog.csdn.net/fangmenghao/article/details/78986165