【问题标题】:Spring-Boot Error Page mapping & NestedServletExceptionSpring-Boot 错误页面映射 & NestedServletException
【发布时间】:2026-01-03 04:50:01
【问题描述】:

我有一个 Spring Boot 应用程序,我在 Tomcat 上作为独立 WAR 文件运行。

我的错误配置中有正常的错误页面映射如下:

@Configuration
class ErrorConfiguration implements EmbeddedServletContainerCustomizer {

  @Override public void customize( ConfigurableEmbeddedServletContainer container ) {
      container.addErrorPages( new ErrorPage( HttpStatus.BAD_REQUEST, "/400" ) )
      container.addErrorPages( new ErrorPage( HttpStatus.FORBIDDEN, "/403" ) )
      container.addErrorPages( new ErrorPage( HttpStatus.NOT_FOUND, "/404" ) )
      container.addErrorPages( new ErrorPage( HttpStatus.METHOD_NOT_ALLOWED, "/405" ) )   
      container.addErrorPages( new ErrorPage( HttpStatus.INTERNAL_SERVER_ERROR, "/500" ) )
      container.addErrorPages( new ErrorPage( HttpStatus.NOT_IMPLEMENTED, "/501" ) )
      container.addErrorPages( new ErrorPage( HttpStatus.BAD_GATEWAY, "/502" ) )
      container.addErrorPages( new ErrorPage( HttpStatus.SERVICE_UNAVAILABLE, "/503" ) )
  }

这一切都很好,但是,我也有一些从其他库抛出的异常,我想映射到特定的错误代码(相当于我想映射到 404/403 等的未找到/未授权等)-但是,在我的控制器中抛出的异常似乎包含在 NestedServletException 中,这意味着当我添加自定义 ErrorPage 与我的异常时,它永远不会正确映射。

有没有办法在不明确捕获异常并将它们作为其他东西重新抛出的情况下解决这个问题?我已经设法通过扩展ErrorPageFilter 并检查此异常并检查根本原因来使其工作,但我不想这样做。

这是设计使然吗?有人遇到并制定了一个优雅的解决方案吗?我想出的两个解决方案是自定义ErrorPageFilter(这不是很好,因为它可能会更难升级版本等)或者有一个全局@ControllerAdvice 异常处理程序来捕获这些异常,然后再次抛出它们 - 任何更好的选择?这是要修复/更改的东西吗?

【问题讨论】:

    标签: java spring spring-mvc spring-boot


    【解决方案1】:

    如果有异常解决您的异常,Spring 将抛出 NestedServletException。我不相信这是你的问题。 :)

    至于将异常(第三方、外部等)映射到 HTTP 状态代码,您可以使用 @ControllerAdvice@ExceptionHandler@ResponseCode 的组合,而不会重新抛出异常。

    @ControllerAdvice
    class CustomExceptionHandler {
        @ResponseStatus(HttpStatus.NOT_FOUND)  // 404
        @ExceptionHandler(SomeThirdPartyException.class)
        public void handleSomeThirdPartyException() {}
    }
    

    【讨论】: