SpringBoot异常处理机制-BasicErrorController与@ControllerAdvice

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());

public ErrorMvcAutoConfiguration(ServerProperties serverProperties, DispatcherServletPath dispatcherServletPath,
			ObjectProvider<ErrorViewResolver> errorViewResolvers) {
		this.serverProperties = serverProperties;
		this.dispatcherServletPath = dispatcherServletPath;
		this.errorViewResolvers = errorViewResolvers.orderedStream().collect(Collectors.toList());
	}

配置类

@Configuration
public class ErrorConfiguration {

    @Bean
    public MyErrorController basicErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties,
                                                  ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) {
        return new MyErrorController(errorAttributes, serverProperties.getError(),
                errorViewResolversProvider.getIfAvailable());
    }


}

@AdviceController

@ControllerAdvice
public class ExceptionHandler {

    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e){

        e.printStackTrace();
        return new Result(StatusCode.ERROR,e.getMessage());

    }

}

拦截器异常&&URL存在,因为URL对应的controller是存在的,所以可以自定义异常处理器,返回前端自定义的协议数据,但是如果没有异常处理器 ,就会出现以下信息。

<!doctype html>
<html lang="en">

<head>
	<title>HTTP Status 500 – Internal Server Error</title>
	<style type="text/css">
		h1 {
			font-family: Tahoma, Arial, sans-serif;
			color: white;
			background-color: #525D76;
			font-size: 22px;
		}

		h2 {
			font-family: Tahoma, Arial, sans-serif;
			color: white;
			background-color: #525D76;
			font-size: 16px;
		}

		h3 {
			font-family: Tahoma, Arial, sans-serif;
			color: white;
			background-color: #525D76;
			font-size: 14px;
		}

		body {
			font-family: Tahoma, Arial, sans-serif;
			color: black;
			background-color: white;
		}

		b {
			font-family: Tahoma, Arial, sans-serif;
			color: white;
			background-color: #525D76;
		}

		p {
			font-family: Tahoma, Arial, sans-serif;
			background: white;
			color: black;
			font-size: 12px;
		}

		a {
			color: black;
		}

		a.name {
			color: black;
		}

		.line {
			height: 1px;
			background-color: #525D76;
			border: none;
		}
	</style>
</head>

<body>
	<h1>HTTP Status 500 – Internal Server Error</h1>
</body>

</html>

统一异常处理的使用:
大多数请情况下,不要去继承重写,BasicErrorController,使用@ControllerAdvice已经是够用的了,因为你的所有请求都会经过Controller

1.拦截器抛出异常,要记得要使url存在,url不存在,会抛出HTTP Status 500 – Internal Server Error异常,尽量不要在拦截器中抛异常吧
2.扩展 org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice 检测返回对象,必要时替换掉
3.拦截器中检测,response 状态码,重写异常数据

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【2021年,将Spring全家桶的课程进行Review,确保不再有课程的顺序错乱,从而导致学员看不懂。进入2022年,将Spring的课程进行整理,整理为案例精讲的系列课程,并开始加入高阶Spring Security等内容,一步步手把手教你从零开始学会应用Spring,课件将逐步进行上传,敬请期待!】 本课程是Spring全家桶系列课程的第三部分Spring Boot,Spring案例精讲课程以真实场景、项目实战为导向,循序渐进,深入浅出的讲解Java网络编程,助力您在技术工作中更进一步。 本课程聚焦Spring Boot核心知识点:整合Web(如:JSP、Thymeleaf、freemarker等的整合)的开发、全局异常处理、配置文件的配置访问、多环境的配置文件设置、日志Logback及slf4j的使用、国际化设置及使用, 并在最后以一个贯穿前后台的Spring Boot整合Mybatis的案例为终奖,使大家快速掌握Spring的核心知识,快速上手,为面试、工作都做好充足的准备。 由于本课程聚焦于案例,即直接上手操作,对于Spring的原理等不会做过多介绍,希望了解原理等内容的需要通过其他视频或者书籍去了解,建议按照该案例课程一步步做下来,之后再去进一步回顾原理,这样能够促进大家对原理有更好的理解。 【通过Spring全家桶,我们保证你能收获到以下几点】 1、掌握Spring全家桶主要部分的开发、实现2、可以使用Spring MVC、Spring Boot、Spring Cloud及Spring Data进行大部分的Spring开发3、初步了解使用微服务、了解使用Spring进行微服务的设计实现4、奠定扎实的Spring技术,具备了一定的独立开发的能力  【实力讲师】 毕业于清华大学软件学院软件工程专业,曾在Accenture、IBM等知名外企任管理及架构职位,近15年的JavaEE经验,近8年的Spring经验,一直致力于架构、设计、开发及管理工作,在电商、零售、制造业等有丰富的项目实施经验  【本课程适用人群】如果你是一定不要错过!  适合于有JavaEE基础的,如:JSP、JSTL、Java基础等的学习者没有基础的学习者跟着课程可以学习,但是需要补充相关基础知识后,才能很好的参与到相关的工作中。 【Spring全家桶课程共包含如下几门】 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值