Spring Boot优雅地处理404异常问题

背景

在使用SpringBoot的过程中,你肯定遇到过404错误。比如下面的代码:

@RestController
@RequestMapping(value = "/hello")
public class HelloWorldController {
  @RequestMapping("/test")
  public Object getObject1(HttpServletRequest request){
    Response response = new Response();
    response.success("请求成功...");
    response.setResponseTime();
    return response;
  }
}

当我们使用错误的请求地址(POST http://127.0.0.1:8888/hello/test1?id=98)进行请求时,会报下面的错误:

{
 "timestamp": "2020-11-19T08:30:48.844+0000",
 "status": 404,
 "error": "Not Found",
 "message": "No message available",
 "path": "/hello/test1"
}

虽然上面的返回很清楚,但是我们的接口需要返回统一的格式,比如:

{
  "rtnCode":"9999",
  "rtnMsg":"404 /hello/test1 Not Found"
}

这时候你可能会想有Spring的统一异常处理,在Controller类上加@RestControllerAdvice注解。但是这种做法并不能统一处理404错误。

404错误产生的原因

产生404的原因是我们调了一个不存在的接口,但是为什么会返回下面的json报错呢?我们先从Spring的源代码分析下。

{
 "timestamp": "2020-11-19T08:30:48.844+0000",
 "status": 404,
 "error": "Not Found",
 "message": "No message available",
 "path": "/hello/test1"
}

为了代码简单起见,这边直接从DispatcherServlet的doDispatch方法开始分析。(如果不知道为什么要从这边开始,你还要熟悉下SpringMVC的源代码)。

... 省略部分代码....
// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
... 省略部分代码

Spring MVC会根据请求URL的不同,配置的RequestMapping的不同,为请求匹配不同的HandlerAdapter。

对于上面的请求地址:http://127.0.0.1:8888/hello/test1?id=98匹配到的HandlerAdapter是HttpRequestHandlerAdapter。

我们直接进入到HttpRequestHandlerAdapter中看下这个类的handle方法。

@Override
@Nullable
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
  throws Exception {
  ((HttpRequestHandler) handler).handleRequest(request, response);
  return null;
}

这个方法没什么内容,直接是调用了HttpRequestHandler类的handleRequest(request, response)方法。所以直接进入这个方法看下吧。

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  // For very general mappings (e.g. "/") we need to check 404 first
  Resource resource = getResource(request);
  if (resource == null) {
    logger.trace("No matching resource found - returning 404");
    // 这个方法很简单,就是设置404响应码,然后将Response的errorState状态从0设置成1
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    // 直接返回
    return;
  }
  ... 省略部分方法
}

这个方法很简单,就是设置404响应码,将Response的errorState状态从0设置成1,然后就返回响应了。整个过程并没有发生任何异常,所以不能触发Spring的全局异常处理机制。

到这边还有一个问题没有解决:就是下面的404提示信息是怎么返回的。

{
 "timestamp": "2020-11-19T08:30:48.844+0000",
 "status": 404,
 "error": "Not Found",
 "message": "No message available",
 "path": "/hello/test1"
}

我们继续往下看。Response响应被返回,进入org.apache.catalina.core.StandardHostValve类的invoke方法进行处理。(不要问我为什么知道是在这里?Debug的能力是需要自己摸索出来的,自己调试多了,你也就会了)

@Override
public final void invoke(Request request, Response response)
  throws IOException, ServletException {

  Context context = request.getContext();
  if (context == null) {
    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              sm.getString("standardHost.noContext"));
    return;
  }

  if (request.isAsyncSupported()) {
    request.setAsyncSupported(context.getPipeline().isAsyncSupported());
  }

  boolean asyncAtStart = request.isAsync();
  boolean asyncDispatching = request.isAsyncDispatching();

  try {
    context.bind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER);
    if (!asyncAtStart && !context.fireRequestInitEvent(request.getRequest())) {
      return;
    }
    try {
      if (!asyncAtStart || asyncDispatching) {
        context.getPipeline().getFirst().invoke(request, response);
      } else {
        if (!response.isErrorReportRequired()) {
          throw new IllegalStateException(sm.getString("standardHost.asyncStateError"));
        }
      }
    } catch (Throwable t) {
      ExceptionUtils.handleThrowable(t);
      container.getLogger().error("Exception Processing " + request.getRequestURI(), t);
      if (!response.isErrorReportRequired()) {
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
        throwable(request, response, t);
      }
    }
    response.setSuspended(false);

    Throwable t = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
    if (!context.getState().isAvailable()) {
      return;
    }
    // 在这里判断请求是不是发生了错误,错误的话就进入StandardHostValve的status(Request request, Response response)方法。
    // Look for (and render if found) an application level error page
    if (response.isErrorReportRequired()) {
      if (t != null) {
        throwable(request, response, t);
      } else {
        status(request, response);
      }
    }

    if (!request.isAsync() && !asyncAtStart) {
      context.fireRequestDestroyEvent(request.getRequest());
    }
  } finally {
    // Access a session (if present) to update last accessed time, based
    // on a strict interpretation of the specification
    if (ACCESS_SESSION) {
      request.getSession(false);
    }
    context.unbind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER);
  }
 }

这个方法会根据返回的响应判断是不是发生了错了,如果发生了error,则进入StandardHostValve的status(Request request, Response response)方法。这个方法“兜兜转转”又进入了StandardHostValve的custom(Request request, Response response,ErrorPage errorPage)方法。这个方法中将请求重新forward到了"/error"接口。

 private boolean custom(Request request, Response response,
               ErrorPage errorPage) {

    if (container.getLogger().isDebugEnabled()) {
      container.getLogger().debug("Processing " + errorPage);
    }
    try {
      // Forward control to the specified location
      ServletContext servletContext =
        request.getContext().getServletContext();
      RequestDispatcher rd =
        servletContext.getRequestDispatcher(errorPage.getLocation());
      if (rd == null) {
        container.getLogger().error(
          sm.getString("standardHostValue.customStatusFailed", errorPage.getLocation()));
        return false;
      }
      if (response.isCommitted()) {
        rd.include(request.getRequest(), response.getResponse());
      } else {
        // Reset the response (keeping the real error code and message)
        response.resetBuffer(true);
        response.setContentLength(-1);
        // 1: 重新forward请求到/error接口
        rd.forward(request.getRequest(), response.getResponse());
        response.setSuspended(false);
      }
      return true;
    } catch (Throwable t) {
      ExceptionUtils.handleThrowable(t);
      container.getLogger().error("Exception Processing " + errorPage, t);
      return false;
    }
  }

上面标号1处的代码重新将请求forward到了/error接口。所以如果我们开着Debug日志的话,你会在后台看到下面的日志。

[http-nio-8888-exec-7] DEBUG org.springframework.web.servlet.DispatcherServlet:891 - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/error]
2020-11-19 19:04:04.280 [http-nio-8888-exec-7] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping:313 - Looking up handler method for path /error
2020-11-19 19:04:04.281 [http-nio-8888-exec-7] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping:320 - Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
2020-11-19 19:04:04.281 [http-nio-8888-exec-7] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory:255 - Returning cached instance of singleton bean 'basicErrorController'

上面是/error的请求日志。到这边还是没说明为什么能返回json格式的404返回格式。我们继续往下看。

到这边为止,我们好像没有任何线索了。但是如果仔细看上面日志的话,你会发现这个接口的处理方法是:

org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]

我们打开BasicErrorController这个类的源代码,一切豁然开朗。

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
  @RequestMapping(produces = "text/html")
  public ModelAndView errorHtml(HttpServletRequest request,
      HttpServletResponse response) {
    HttpStatus status = getStatus(request);
    Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
        request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
    response.setStatus(status.value());
    ModelAndView modelAndView = resolveErrorView(request, response, status, model);
    return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
  }

  @RequestMapping
  @ResponseBody
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
    Map<String, Object> body = getErrorAttributes(request,
        isIncludeStackTrace(request, MediaType.ALL));
    HttpStatus status = getStatus(request);
    return new ResponseEntity<Map<String, Object>>(body, status);
  }
  ... 省略部分方法
}

BasicErrorController是Spring默认配置的一个Controller,默认处理/error请求。BasicErrorController提供两种返回错误一种是页面返回、当你是页面请求的时候就会返回页面,另外一种是json请求的时候就会返回json错误。

自定义404错误处理类

我们先看下BasicErrorController是在哪里进行配置的。

在IDEA中,查看BasicErrorController的usage,我们发现这个类是在ErrorMvcAutoConfiguration中自动配置的。

@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class })
// Load before the main WebMvcAutoConfiguration so that the error View is available
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties({ ServerProperties.class, ResourceProperties.class })
public class ErrorMvcAutoConfiguration {

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

从上面的配置中可以看出来,只要我们自己配置一个ErrorController,就可以覆盖掉BasicErrorController的行为。

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

  @Value("${server.error.path:${error.path:/error}}")
  private String path;

  public CustomErrorController(ServerProperties serverProperties) {
    super(new DefaultErrorAttributes(), serverProperties.getError());
  }

  /**
   * 覆盖默认的JSON响应
   */
  @Override
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {

    HttpStatus status = getStatus(request);
    Map<String, Object> map = new HashMap<String, Object>(16);
    Map<String, Object> originalMsgMap = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
    String path = (String)originalMsgMap.get("path");
    String error = (String)originalMsgMap.get("error");
    String message = (String)originalMsgMap.get("message");
    StringJoiner joiner = new StringJoiner(",","[","]");
    joiner.add(path).add(error).add(message);
    map.put("rtnCode", "9999");
    map.put("rtnMsg", joiner.toString());
    return new ResponseEntity<Map<String, Object>>(map, status);
  }

  /**
   * 覆盖默认的HTML响应
   */
  @Override
  public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
    //请求的状态
    HttpStatus status = getStatus(request);
    response.setStatus(getStatus(request).value());
    Map<String, Object> model = getErrorAttributes(request,
        isIncludeStackTrace(request, MediaType.TEXT_HTML));
    ModelAndView modelAndView = resolveErrorView(request, response, status, model);
    //指定自定义的视图
    return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
  }
}

默认的错误路径是/error,我们可以通过以下配置进行覆盖:

server:
 error:
  path: /xxx

更详细的内容请参考Spring Boot的章节。

简单总结#

  • 如果在过滤器(Filter)中发生异常,或者调用的接口不存在,Spring会直接将Response的errorStatus状态设置成1,将http响应码设置为500或者404,Tomcat检测到errorStatus为1时,会将请求重现forward到/error接口;
  • 如果请求已经进入了Controller的处理方法,这时发生了异常,如果没有配置Spring的全局异常机制,那么请求还是会被forward到/error接口,如果配置了全局异常处理,Controller中的异常会被捕获;
  • 继承BasicErrorController就可以覆盖原有的错误处理方式。

到此这篇关于Spring Boot优雅地处理404异常的文章就介绍到这了,更多相关Spring Boot 404异常内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringBoot配置SwaggerUI访问404错误的解决方法

    SpringBoot 配置SwaggerUI 访问404的小坑. 在学习SpringBoot构建Restful API的时候遇到了一个小坑,配置Swagger UI的时候无法访问. 首先在自己的pom文件中加入Swagger的依赖,如下所示: <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version&

  • 解决Spring Boot 在localhost域奇怪的404问题(Mac book pro)

    在mac系统中,明明url是对的,浏览器也可以打开,一个简单的代码调用就是404,你有没有遇到过? 情景再现 普通的一个controller,返回一个常量. @GetMapping("/project_metadata/spring-boot") public String getMetadata(){ return "{\"data\":1234}";//这个不重要 } 调用接口的方式: content = new JSONObject(res

  • 解决Spring Boot 正常启动后访问Controller提示404问题

    问题描述 今天重新在搭建Spring Boot项目的时候遇到访问Controller报404错误,之前在搭建的时候没怎么注意这块.新创建项目成功后,作为项目启动类的Application在com.blog.start包下面,然后我写了一个Controller,然后包的路径是com.blog.ty.controller用的@RestController 注解去配置的controller,然后路径也搭好了,但是浏览器一直报404.最后找到原因是Spring Boot只会扫描启动类当前包和以下的包 ,

  • BGPMPLS VPN的实现技术

    BGP/MPLS VPN的实现技术 摘要 MPLS VPN技术是未来构建VPN的发展方向,越来越受到客户和运营商的青睐.BGP/MPLS VPN是第三层MPLS VPN技术.本文在对VRF.RD.RT几个重要概念进行解释之后,对BGP/MPLS VPN的数据转发过程和路由信息分发过程进行了较为详细的叙述.最后通过分析BGP/MPLS VPN的特点,分析了其市场前景. 关键词 多协议标签交换(MPLS) 虚拟局域网(VPN) 一.VPN技术概述 VPN(Virtual Private Networ

  • SpringBoot拦截器实现对404和500等错误的拦截

    今天给大家介绍一下SpringBoot中拦截器的用法,相比Struts2中的拦截器,SpringBoot的拦截器就显得更加方便简单了. 只需要写几个实现类就可以轻轻松松实现拦截器的功能了,而且不需要配置任何多余的信息,对程序员来说简直是一种福利啊. 废话不多说,下面开始介绍拦截器的实现过程: 第一步:创建我们自己的拦截器类并实现 HandlerInterceptor 接口. package example.Interceptor; import javax.servlet.http.HttpSe

  • Spring Boot优雅地处理404异常问题

    背景 在使用SpringBoot的过程中,你肯定遇到过404错误.比如下面的代码: @RestController @RequestMapping(value = "/hello") public class HelloWorldController { @RequestMapping("/test") public Object getObject1(HttpServletRequest request){ Response response = new Resp

  • spring boot整合mongo查询converter异常排查记录

    目录 前言 自定义转换器 javabean的方式配置MongoTemplate 后记: 前言 使用过spring boot的人都知道spring boot约定优于配置的理念给我们开发中集成相关技术框架提供了很多的便利,集成mongo也是相当的简单,但是通过约定的配置信息来集成mongo有些问题. 当你的字段包含Timestamp这种类型时,读取数据的时候会抛一个类型转换的异常,如 No converter found capable of converting from type [java.u

  • Spring Boot 优雅整合多数据源

    目录 何时用到多数据源 整合单一的数据源 整合Mybatis 多数据源如何整合? 什么是动态数据源? 数据源切换如何保证线程隔离? 如何构造一个动态数据源? 定义一个注解 如何与Mybatis整合? 演示 总结 前言: 什么是多数据源?最常见的单一应用中最多涉及到一个数据库,即是一个数据源(Datasource).那么顾名思义,多数据源就是在一个单一应用中涉及到了两个及以上的数据库了. 其实在配置数据源的时候就已经很明确这个定义了,如以下代码: @Bean(name = "dataSource&

  • Spring Boot FeignClient 如何捕获业务异常信息

    Spring Boot FeignClient 捕获业务异常信息 因项目重构采用spring cloud,feign不可避免.目前spring cloud在国内还不是很成熟,所以踩坑是免不了的.最近处理全局异常的问题,搜了个遍也没找到合适的解决方案 1.全局异常处理 import com.bossien.common.comm.entity.ResponseDto; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import o

  • spring boot教程之全局处理异常封装

    1|1简介 在项目中经常出现系统异常的情况,比如NullPointerException等等.如果默认未处理的情况下,springboot会响应默认的错误提示,这样对用户体验不是友好,系统层面的错误,用户不能感知到,即使为500的错误,可以给用户提示一个类似服务器开小差的友好提示等. 在微服务里,每个服务中都会有异常情况,几乎所有服务的默认异常处理配置一致,导致很多重复编码,我们将这些重复默认异常处理可以抽出一个公共starter包,各个服务依赖即可,定制化异常处理在各个模块里开发. 1|2配置

  • Spring Boot详细打印启动时异常堆栈信息详析

    前言 SpringBoot在项目启动时如果遇到异常并不能友好的打印出具体的堆栈错误信息,我们只能查看到简单的错误消息,以致于并不能及时解决发生的问题,针对这个问题SpringBoot提供了故障分析仪的概念(failure-analyzer),内部根据不同类型的异常提供了一些实现,我们如果想自定义该怎么去做? FailureAnalyzer SpringBoot提供了启动异常分析接口FailureAnalyzer,该接口位于org.springframework.boot.diagnosticsp

  • Spring Boot优雅使用RocketMQ的方法实例

    前言 MQ,是一种跨进程的通信机制,用于上下游传递消息.在传统的互联网架构中通常使用MQ来对上下游来做解耦合. 举例:当A系统对B系统进行消息通讯,如A系统发布一条系统公告,B系统可以订阅该频道进行系统公告同步,整个过程中A系统并不关系B系统会不会同步,由订阅该频道的系统自行处理. 什么是RocketMQ?# 官方说明: 随着使用越来越多的队列和虚拟主题,ActiveMQ IO模块遇到了瓶颈.我们尽力通过节流,断路器或降级来解决此问题,但效果不佳.因此,我们那时开始关注流行的消息传递解决方案Ka

  • Spring Boot如何优雅的使用多线程实例详解

    前言 本文带你快速了解@Async注解的用法,包括异步方法无返回值.有返回值,最后总结了@Async注解失效的几个坑. 在 SpringBoot 应用中,经常会遇到在一个接口中,同时做事情1,事情2,事情3,如果同步执行的话,则本次接口时间取决于事情1 2 3执行时间之和:如果三件事同时执行,则本次接口时间取决于事情1 2 3执行时间最长的那个,合理使用多线程,可以大大缩短接口时间.那么在 SpringBoot 应用中如何优雅的使用多线程呢? Don't bb, show me code. 快速

  • 详解Spring Boot最新版优雅停机的方法

    什么是优雅停机 先来一段简单的代码,如下: @RestController public class DemoController { @GetMapping("/demo") public String demo() throws InterruptedException { // 模拟业务耗时处理流程 Thread.sleep(20 * 1000L); return "hello"; } } 当我们流量请求到此接口执行业务逻辑的时候,若服务端此时执行关机 (ki

  • spring boot 如何优雅关闭服务

    spring boot 优雅的关闭服务 实现ContextClosedEvent 监听器,监听到关闭事件后,关闭springboot进程 ** 网上有很多例子 使用spring boot 插件做关闭经测试此插件只能是关闭spring boot服务,不能杀死服务进程.还是需要实现关闭监听,去杀死进程. 网上有很多例子 使用spring boot 插件做关闭经测试此插件只能是关闭spring boot服务,不能杀死服务进程.还是需要实现关闭监听,去杀死进程. 网上有很多例子 使用spring boo

随机推荐