springboot 配置全局404详细步骤及说明

  • application.xml中配置如下
server:
  error:
    whitelabel:
      enabled: false
    include-exception: true
    include-stacktrace: on_trace_param

说明:server.error.whitelabel.enabled,是为了去掉springboot的自动配置,它的自动配置代码如下:

org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration.WhitelabelErrorViewConfiguration

	@Configuration
	@ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true)
	@Conditional(ErrorTemplateMissingCondition.class)
	protected static class WhitelabelErrorViewConfiguration {

		private final StaticView defaultErrorView = new StaticView();

		@Bean(name = "error")
		@ConditionalOnMissingBean(name = "error")
		public View defaultErrorView() {
			return this.defaultErrorView;
		}

		// If the user adds @EnableWebMvc then the bean name view resolver from
		// WebMvcAutoConfiguration disappears, so add it back in to avoid disappointment.
		@Bean
		@ConditionalOnMissingBean
		public BeanNameViewResolver beanNameViewResolver() {
			BeanNameViewResolver resolver = new BeanNameViewResolver();
			resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
			return resolver;
		}

	}

server.error.include-exception 用于实例化一个bean可以获取对应的404发生的时候获取对应的错误信息:

	@Bean
	@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
	public DefaultErrorAttributes errorAttributes() {
		return new DefaultErrorAttributes(
				this.serverProperties.getError().isIncludeException());
	}

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

  • application.yml中还需要配置如下信息:

spring:
  mvc:
    favicon:
      enabled: false
    throw-exception-if-no-handler-found: true
  • 重写一个controller实现ErrorController, 因为ErrorMvcAutoConfiguration会查找所有实现了ErrorController 的bean,如果没有就使用自己的BasicErrorController:
@Bean
	@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
	public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
		return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
				this.errorViewResolvers);
	}

所以重写的一个自定义的ErrorController如下:


/**
 * @author Walter
 * @see org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
 * @see org.springframework.boot.autoconfigure.web.ErrorProperties
 * @see org.springframework.boot.autoconfigure.web.ServerProperties
 */
@RestController
@Slf4j
public class GlobalNotFoundErrorController implements ErrorController {
    private static final String PATH = "/error";

    private ErrorAttributes errorAttributes;

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

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

    @RequestMapping(value = PATH)
    public WebResponse handle404Exception(HttpServletRequest request) {
        WebResponse response = WebResponse.getResponse();
        final String requestURI = request.getRequestURI();
        WebRequest webRequest = new ServletWebRequest(request);
        Map<String, Object> body = errorAttributes.getErrorAttributes(webRequest, true);
        log.error("没有找到请求地址: {},异常返回结果: {}", requestURI, body);
        /* int internalStatusCode = (int) body.get("active"); */
        body.remove("active");
        body.remove("timestamp");
        body.remove("message");
//        HttpStatus active = getStatus(request);
        response.fail(WebResponseCode.FAILED, body, requestURI);
        return response;
    }
}

最后更新: 5/25/2019, 10:16:53 PM
本文浏览量