如何在 Dropwizard 中查看自定义 404 页面

How to view custom 404 page in Dropwizard

任何人都可以告诉我如何查看我的自定义 404 页面。我用谷歌搜索并尝试实施 ExceptionMapper<RuntimeException> 但这并没有完全奏效。我使用的是 0.8.1 版本

我的异常映射器:

public class RuntimeExceptionMapper implements ExceptionMapper<NotFoundException> {
    @Override
    public Response toResponse(NotFoundException exception) {
        Response defaultResponse = Response.status(Status.OK)
            .entity(JsonUtils.getErrorJson("default response"))
            .build();
        return defaultResponse;
    }
}

这仅适用于不正确的 API,不适用于资源调用

我的设置:

@Override
public void initialize(Bootstrap<WebConfiguration> bootstrap) {
    bootstrap.addBundle(new AssetsBundle("/webapp", "/", "index.html"));
}

@Override
public void run(WebConfiguration configuration, Environment environment) throws Exception {
    environment.jersey().register(RuntimeExceptionMapper.class);
    ((AbstractServerFactory) configuration.getServerFactory()).setJerseyRootPath("/api/*");

    // Registering Resources
    environment.jersey().register(new AuditResource(auditDao));
    ....
}

现在,

http://localhost:8080/api/rubish 通过覆盖的 ExceptionMapper 方法 http://localhost:8080/rubish.html 导致默认 404 页面

我如何设置以便每当请求未知页面时 dropwizard 将显示自定义 404 页面

我为异常映射器this link 推荐

如果我没理解错的话,您想要的是为不匹配的资源请求提供自定义 404 页面。为此,您可以编写一个单独的资源 class 并在其中编写一个单独的资源方法。这个资源方法应该有一个

@Path("/{default: .*}")

注释。此资源方法捕获不匹配的资源请求。在这种方法中,您可以提供自己的自定义视图。

为了清楚起见,请查看下面的代码片段,

@Path("/")
public class DefaultResource {

  /**
   * Default resource method which catches unmatched resource requests. A page not found view is
   * returned.
   */
  @Path("/{default: .*}")
  @GET
  public View defaultMethod() throws URISyntaxException {
    // Return a page not found view.
    ViewService viewService = new ViewService();
    View pageNotFoundView = viewService.getPageNotFoundView();
    return pageNotFoundView;
  }

}

如果您不知道如何使用 dropwizard 提供静态资产,可以参考 this 或者问我。

要为任何错误配置自定义错误页面,您可以像这样在应用程序中配置 ErrorPageErrorHandler:

@Override
public void run(final MonolithConfiguration config,
                final Environment env) {
    ErrorPageErrorHandler eph = new ErrorPageErrorHandler();
    eph.addErrorPage(404, "/error/404");
    env.getApplicationContext().setErrorHandler(eph);
}

然后像这样创建一个资源:

@Path("/error")
public class ErrorResource {

    @GET
    @Path("404")
    @Produces(MediaType.TEXT_HTML)
    public Response error404() {
       return Response.status(Response.Status.NOT_FOUND)
                      .entity("<html><body>Error 404 requesting resource.</body></html>")
                      .build();
    }

为了以防万一,这里还有 ErrorPageErrorHandler 的导入:

import org.eclipse.jetty.servlet.ErrorPageErrorHandler;