Whitelabel Error Page 專題


根據不一樣的Accept,Whitelabel 會展示不一樣的representation:
(1)Accept:application/json


(2)Accept:text/html



(3)Accept:application/xml
html

w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by handler execution: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

 
Accept:text/html 時,api接口不存在時,後端會打印的錯誤日誌【這種大量打印錯誤日誌的行爲,會不會形成IO阻塞,並使服務器掛掉】:
spring webmvc的版本:5.0.9.RELEASE

java

2018-12-13 16:03:39.799 ERROR 14912 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] threw exception

javax.servlet.ServletException: Circular view path [error]: would dispatch back to the current handler URL [/error] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
    at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:209) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:147) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:315) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1069) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1008) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:472) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:395) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:316) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:395) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:177) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_144]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]

2018-12-13 16:03:39.801 ERROR 14912 --- [nio-8080-exec-6] o.a.c.c.C.[Tomcat].[localhost]           : Exception Processing ErrorPage[errorCode=0, location=/error]

javax.servlet.ServletException: Circular view path [error]: would dispatch back to the current handler URL [/error] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
    at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:209) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:147) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:315) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1069) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1008) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:472) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:395) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:316) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:395) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:177) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_144]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]

 

 

 

Spring boot爲錯誤視圖提供了以下錯誤屬性:
timestamp:錯誤發生的時間
status:HTTP狀態碼
error:錯誤緣由
exception:異常的類名
message:異常消息(若是這個錯誤是由異常引發的)
errors:BindsResult異常裏的各類錯誤(若是這個錯誤是由異常引發的)
trace:異常跟蹤信息(若是這個錯誤是由異常引發的)
path:錯誤發生時請求的URL路徑web

test To switch it off you can set server.error.whitelabel.enabled=falsespring

 

錯誤問題會發生的,那些在生產環境裏最健壯的應用程序偶爾也會遇到麻煩。雖然減小用戶遇到錯誤的機率很重要,但讓應用程序展示一個好的錯誤頁面也一樣重要express

Spring Boot默認提供這個whitelabel錯誤頁,是自動配置的一部分。apache

Spring Boot自動配置的默認錯誤處理器會查找名爲error的視圖,若是找不到就用默認的whitelabel視圖。所以最簡單的方法就是建立一個自定義視圖,讓解析出的視圖名爲error
要達到預期的效果,須要有下面一項視圖解析器的配置:
(1)實現了Spring的View接口的Bean,其ID爲error(由Spring的BeanNameViewResolver所解析)
(2)若是配置了Thymeleaf,則有名爲error.html的Thymeleaf模板
(3)若是配置了FreeMarker,則有名爲error.ftl的FreeMarker模板
(4)若是配置了Velocity,則有名爲error.vm的Velocity模板
(5)若是是用JSP視圖,則有名爲error.jsp的JSP模板

固然視圖解析器要知道這個error的模板文件。


json

 

異常說明
SpringBoot搭建的接口服務,若是請求非註冊類的無效接口地址,則返回該頁面。主要問題就是沒有對異常請求作處理。後端

舉例,定義有效接口地址如:http://ip/user, http://ip/age。則其它地址均爲無效地址,若請求則返回上述Whitelabel Error Page頁面。api

 

2.0 異常處理tomcat

主要是添加一個AppErrorController的Controller類,這裏我定義了異常返回頁面。

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class AppErrorController implements ErrorController{

    private static final Logger logger = LoggerFactory.getLogger(AppErrorController.class);

    private static AppErrorController appErrorController;

     /**
     * Error Attributes in the Application
     */
    @Autowired
    private ErrorAttributes errorAttributes;

    private final static String ERROR_PATH = "/error";

    /**
     * Controller for the Error Controller
     * @param errorAttributes
     * @return 
     */ 

    public AppErrorController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    public AppErrorController() {
        if(appErrorController == null){
            appErrorController = new AppErrorController(errorAttributes);
        }
    }

    /**
     * Supports the HTML Error View
     * @param request
     * @return
     */
    @RequestMapping(value = ERROR_PATH, produces = "text/html")
    public ModelAndView errorHtml(HttpServletRequest request) {
        return new ModelAndView("greeting", getErrorAttributes(request, false));
    }

    /**
     * Supports other formats like JSON, XML
     * @param request
     * @return
     */
    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, getTraceParameter(request));
        HttpStatus status = getStatus(request);
        return new ResponseEntity<Map<String, Object>>(body, status);
    }

    /**
     * Returns the path of the error page.
     *
     * @return the error path
     */
    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }


    private boolean getTraceParameter(HttpServletRequest request) {
        String parameter = request.getParameter("trace");
        if (parameter == null) {
            return false;
        }
        return !"false".equals(parameter.toLowerCase());
    }

    private Map<String, Object> getErrorAttributes(HttpServletRequest request,
                                                   boolean includeStackTrace) {     
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);       
        Map<String, Object> map = this.errorAttributes.getErrorAttributes(requestAttributes,includeStackTrace);  
        String URL = request.getRequestURL().toString();
        map.put("URL", URL);        
        logger.debug("AppErrorController.method [error info]: status-" + map.get("status") +", request url-" + URL);            
        return map;
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode != null) {
            try {
                return HttpStatus.valueOf(statusCode);
            }
            catch (Exception ignored) {
            }
        }
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }   

}

這個類實現了ErrorController接口,用來處理請求的各類異常。其中定義了一個greeting的html模版,用來顯示返回結果。
初始化此類模版須要在pom中加入如下依賴:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

這個依賴主要是給SpringBoot中加載html等類型的模版服務。其支持的模版類型以下:

Template modes:
[THYMELEAF]     * XHTML
[THYMELEAF]     * XML
[THYMELEAF]     * HTML5
[THYMELEAF]     * LEGACYHTML5
[THYMELEAF]     * VALIDXHTML
[THYMELEAF]     * VALIDXML

org.thymeleaf.templatemode.TemplateMode

/*
 * =============================================================================
 *
 *   Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org)
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 * =============================================================================
 */
package org.thymeleaf.templatemode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver;

/**
 *
 * @author Daniel Fern&aacute;ndez
 *
 * @since 3.0.0
 *
 */
public enum TemplateMode {


    HTML(true, false, false), XML(false, true, false),
    TEXT(false, false, true), JAVASCRIPT(false, false, true), CSS(false, false, true),
    RAW(false, false, false),


    /**
     * Provided only for legacy compatibility reasons for old XML-based configurations (e.g. Spring).
     * <strong>Never</strong> use this value directly. Only to be used internally at
     * {@link AbstractConfigurableTemplateResolver} implementations.
     *
     * @deprecated Deprecated in 3.0.0. Use {@link #HTML} instead. Will be REMOVED in 3.1
     */
    @Deprecated
    HTML5(true, false, false),

    /**
     * Provided only for legacy compatibility reasons for old XML-based configurations (e.g. Spring).
     * <strong>Never</strong> use this value directly. Only to be used internally at
     * {@link AbstractConfigurableTemplateResolver} implementations.
     *
     * @deprecated Deprecated in 3.0.0. Use {@link #HTML} instead. Will be REMOVED in 3.1
     */
    @Deprecated
    LEGACYHTML5(true, false, false),

    /**
     * Provided only for legacy compatibility reasons for old XML-based configurations (e.g. Spring).
     * <strong>Never</strong> use this value directly. Only to be used internally at
     * {@link AbstractConfigurableTemplateResolver} implementations.
     *
     * @deprecated Deprecated in 3.0.0. Use {@link #HTML} instead. Will be REMOVED in 3.1
     */
    @Deprecated
    XHTML(true, false, false),

    /**
     * Provided only for legacy compatibility reasons for old XML-based configurations (e.g. Spring).
     * <strong>Never</strong> use this value directly. Only to be used internally at
     * {@link AbstractConfigurableTemplateResolver} implementations.
     *
     * @deprecated Deprecated in 3.0.0. Use {@link #HTML} instead. Will be REMOVED in 3.1
     */
    @Deprecated
    VALIDXHTML(true, false, false),

    /**
     * Provided only for legacy compatibility reasons for old XML-based configurations (e.g. Spring).
     * <strong>Never</strong> use this value directly. Only to be used internally at
     * {@link AbstractConfigurableTemplateResolver} implementations.
     *
     * @deprecated Deprecated in 3.0.0. Use {@link #XML} instead. Will be REMOVED in 3.1
     */
    @Deprecated
    VALIDXML(false, true, false);





    private static Logger logger = LoggerFactory.getLogger(TemplateMode.class);


    private final boolean html;
    private final boolean xml;
    private final boolean text;
    private final boolean caseSensitive;

    TemplateMode(final boolean html, final boolean xml, final boolean text) {
        this.html = html;
        this.xml = xml;
        this.text = text;
        this.caseSensitive = !this.html;
    }

    public boolean isMarkup() {
        return this.html || this.xml;
    }

    public boolean isText() {
        return this.text;
    }

    public boolean isCaseSensitive() {
        return this.caseSensitive;
    }


    public static TemplateMode parse(final String mode) {
        if (mode == null || mode.trim().length() == 0) {
            throw new IllegalArgumentException("Template mode cannot be null or empty");
        }
        if ("HTML".equalsIgnoreCase(mode)) { return HTML;
        }
        if ("XML".equalsIgnoreCase(mode)) {
            return XML;
        }
        if ("TEXT".equalsIgnoreCase(mode)) {
            return TEXT;
        }
        if ("JAVASCRIPT".equalsIgnoreCase(mode)) {
            return JAVASCRIPT;
        }
        if ("CSS".equalsIgnoreCase(mode)) {
            return CSS;
        }
        if ("RAW".equalsIgnoreCase(mode)) {
            return RAW;
        }
        // Legacy template modes are automatically converted here
        // This code should probably be removed at some point in the distant future after Thymeleaf v3
        if ("HTML5".equalsIgnoreCase(mode) || "XHTML".equalsIgnoreCase(mode) ||
                "VALIDXHTML".equalsIgnoreCase(mode) || "LEGACYHTML5".equalsIgnoreCase(mode)) {
            logger.warn(
                    "[THYMELEAF][{}] Template Mode '{}' is deprecated. Using Template Mode '{}' instead.",
                    new Object[]{TemplateEngine.threadIndex(), mode, HTML});
            return HTML;
        }
        if ("VALIDXML".equalsIgnoreCase(mode)) {
            logger.warn(
                    "[THYMELEAF][{}] Template Mode '{}' is deprecated. Using Template Mode '{}' instead.",
                    new Object[]{TemplateEngine.threadIndex(), mode, XML});
            return XML;
        }
        logger.warn(
                "[THYMELEAF][{}] Unknown Template Mode '{}'. Must be one of: 'HTML', 'XML', 'TEXT', 'JAVASCRIPT', 'CSS', 'RAW'. " +
                "Using default Template Mode '{}'.",
                new Object[]{TemplateEngine.threadIndex(), mode, HTML});
        return HTML;
    }

}

SpringBoot項目配置模版路徑的方法以下:

一、在main的resources路徑下新建templates文件夾

二、在templates文件夾中新建模版文件greeting.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Error Pages</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text="'Url:' + ${URL}" />
    <p th:text="'Error:' + ${error}" />
    <p th:text="'Status:' + ${status}" />
    <p th:text="'Timestamp:' + ${timestamp}" />
</body>
</html>

3.0 處理結果
無效請求地址均會返回此頁面,只是其中的返回值不一樣。

Spring Boot Remove Whitelabel Error Page:

You need to change your code to the following:

@RestController
public class IndexController implements ErrorController{

    private static final String PATH = "/error";

    @RequestMapping(value = PATH)
    public String error() {
        return "Error handling";
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}

Your code did not work, because Spring Boot automatically registers the BasicErrorController as a Spring Bean when you have not specified an implementation of ErrorController.
To see that fact just navigate to ErrorMvcAutoConfiguration.basicErrorController

You can remove it completely by specifying:

import org.springframework.context.annotation.Configuration;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
...
@Configuration
@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
public static MainApp { 
  ... 
}

However, do note that doing so will probably cause servlet container's whitelabel pages to show up instead :)

EDIT: Another way to do this is via application.yaml. Just put in the value:

spring:
  autoconfigure:
    exclude: org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration

https://stackoverflow.com/questions/25356781/spring-boot-remove-whitelabel-error-page

相關文章
相關標籤/搜索