亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring Boot優(yōu)雅地處理404異常問題

 更新時間:2020年11月20日 09:48:02   作者:程序員自由之路  
這篇文章主要介紹了Spring Boot優(yōu)雅地處理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"
}

雖然上面的返回很清楚,但是我們的接口需要返回統(tǒng)一的格式,比如:

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

這時候你可能會想有Spring的統(tǒng)一異常處理,在Controller類上加@RestControllerAdvice注解。但是這種做法并不能統(tǒng)一處理404錯誤。

404錯誤產(chǎn)生的原因

產(chǎn)生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會根據(jù)請求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狀態(tài)從0設置成1
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    // 直接返回
    return;
  }
  ... 省略部分方法
}

這個方法很簡單,就是設置404響應碼,將Response的errorState狀態(tài)從0設置成1,然后就返回響應了。整個過程并沒有發(fā)生任何異常,所以不能觸發(fā)Spring的全局異常處理機制。

到這邊還有一個問題沒有解決:就是下面的404提示信息是怎么返回的。

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

我們繼續(xù)往下看。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;
    }
    // 在這里判斷請求是不是發(fā)生了錯誤,錯誤的話就進入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);
  }
 }

這個方法會根據(jù)返回的響應判斷是不是發(fā)生了錯了,如果發(fā)生了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返回格式。我們繼續(xù)往下看。

到這邊為止,我們好像沒有任何線索了。但是如果仔細看上面日志的話,你會發(fā)現(xiàn)這個接口的處理方法是:

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,我們發(fā)現(xiàn)這個類是在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) {
    //請求的狀態(tài)
    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的章節(jié)。

簡單總結#

  • 如果在過濾器(Filter)中發(fā)生異常,或者調用的接口不存在,Spring會直接將Response的errorStatus狀態(tài)設置成1,將http響應碼設置為500或者404,Tomcat檢測到errorStatus為1時,會將請求重現(xiàn)forward到/error接口;
  • 如果請求已經(jīng)進入了Controller的處理方法,這時發(fā)生了異常,如果沒有配置Spring的全局異常機制,那么請求還是會被forward到/error接口,如果配置了全局異常處理,Controller中的異常會被捕獲;
  • 繼承BasicErrorController就可以覆蓋原有的錯誤處理方式。

到此這篇關于Spring Boot優(yōu)雅地處理404異常的文章就介紹到這了,更多相關Spring Boot 404異常內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • java單例模式實現(xiàn)面板切換

    java單例模式實現(xiàn)面板切換

    這篇文章主要為大家詳細介紹了java單例模式實現(xiàn)面板切換,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-11-11
  • spring中@RestController和@Controller的區(qū)別小結

    spring中@RestController和@Controller的區(qū)別小結

    @RestController和@Controller這兩個注解用于創(chuàng)建Web應用程序的控制器類,那么這兩個注解有哪些區(qū)別,本文就來介紹一下,并用示例代碼說明,感興趣的可以了解一下
    2023-09-09
  • Java創(chuàng)建文件且寫入內容的方法

    Java創(chuàng)建文件且寫入內容的方法

    這篇文章主要介紹了Java創(chuàng)建文件且寫入內容的方法的相關資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2016-07-07
  • mybatis-plus 如何配置邏輯刪除

    mybatis-plus 如何配置邏輯刪除

    這篇文章主要介紹了mybatis-plus 如何配置邏輯刪除,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • Spring連接Mysql數(shù)據(jù)庫全過程

    Spring連接Mysql數(shù)據(jù)庫全過程

    這篇文章主要介紹了Spring連接Mysql數(shù)據(jù)庫全過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • SpringBoot中時間格式化的五種方法匯總

    SpringBoot中時間格式化的五種方法匯總

    時間格式化在項目中使用頻率是非常高的,這篇文章主要給大家介紹了關于SpringBoot中時間格式化的五種方法,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下
    2021-07-07
  • Java9新特性中的模塊化詳解

    Java9新特性中的模塊化詳解

    今天介紹一個Java?9的功能,模塊化(Modular),這可能使Java有史以來最大的Feature,對Java9模塊化相關知識感興趣的朋友一起看看吧
    2022-03-03
  • 淺析javax.servlet.Servlet,ServletContext接口

    淺析javax.servlet.Servlet,ServletContext接口

    本篇文章是對javax.servlet.Servlet,ServletContext接口進行了纖細的分析介紹,需要的朋友參考下
    2013-07-07
  • java常見事件響應方法實例匯總

    java常見事件響應方法實例匯總

    這篇文章主要介紹了java常見事件響應方法,對于初學者有很好的參考借鑒價值,分享給大家,需要的朋友可以參考下
    2014-08-08
  • SpringBoot項目集成Swagger和swagger-bootstrap-ui及常用注解解讀

    SpringBoot項目集成Swagger和swagger-bootstrap-ui及常用注解解讀

    這篇文章主要介紹了SpringBoot項目集成Swagger和swagger-bootstrap-ui及常用注解解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03

最新評論