How to view a custom 404 page in Dropwizard

can anyone tell me how to view my 404 page. I googled and tried to implement ExceptionMapper<RuntimeException>, but this did not work completely. I am using version 0.8.1

My Exception mapper:

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;
    }
}

This only works with the wrong APIs and not with resource calls

My setup:

@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));
    ....
}

Now,

http://localhost:8080/api/rubishgoes through an overridden method ExceptionMapper http://localhost:8080/rubish.htmldisplays 404 pages by default

How to set up dropwizard to display 404 user page when requesting unknown pages

I referenced this link for the exception linker

+4
2

, 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;
+2

, 404 . .

@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;
  }

}

this, , dropwizard .

+1

Source: https://habr.com/ru/post/1629203/


All Articles