Question

Does anyone know how to override existing 404 error page when using Spark micro web framework ?

The default error page is:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/>
<title>Error 404 </title>
</head>
<body>
<h2>HTTP ERROR: 404</h2>
<p>Problem accessing /strangepage. Reason:
<pre>    Not Found</pre></p>
<hr /><i><small>Powered by Jetty://</small></i>
</body>
</html>

I want to edit this custom error page (or maybe redirect it to a another route) :

get(new Route("/404") {
   @Override
   public Object handle(Request request, Response response) {
       response.type("text/html");
       return "Error page 404";
   }
});
Was it helpful?

Solution 2

This is an old question, but since it is still answered.

Now you can handedl 404 as follows :

notFound("<html><body><h1>Custom 404 handling</h1></body></html>");

OTHER TIPS

Try to use this tip below

Add these lines right after last route because Spark cares about order

Spark.get("*", (req, res) -> {    
    if(!req.pathInfo().startsWith("/static")){
        res.status(404);
        return TEMPLATE_ENGINE.render(ModelAndView modelAndView);
    }
    return null;
});

All request (include static request) doesn't match all upper routes which will be catch here. So that, you have to separate strange requests and static request with IF statement. You should return your error html page as string here.

All static request is handled by another handler, and you must return NULL to force Spark call another handler as normal case.

if you deploy your app on a webserver you could could map an error to a spark route.

<filter>
    <filter-name>SparkFilter</filter-name>
    <filter-class>spark.servlet.SparkFilter</filter-class>
    <init-param>
        <param-name>applicationClass</param-name>
        <param-value>com.company.YourApplication</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>SparkFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>

<error-page>
    <error-code>404</error-code>
    <location>/404</location> <!-- this is your route-->
</error-page>

I think you can use a Spark Filter. To filter out the routes which are not allowed. You can render a new template in the filter.

This is an example from the docs.

before(new Filter() { // matches all routes
    @Override
    public void handle(Request request, Response response) {
        boolean authenticated;
        // ... check if authenticated
        if (!authenticated) {
            halt(401, "You are not welcome here");
        }
    }
 });

In Spark 2.3 documentation:

get("/throwexception", (request, response) -> {
    throw new NotFoundException();
});

exception(NotFoundException.class, (e, request, response) -> {
    response.status(404);
    response.body("Resource not found");
});

I have found that instead of "/throwexception", "/*" gets all not found pages. This may not work if you have more complicated url structure than what I am doing. I was unable to resolve NotFoundException in my project so I think you can make your own exception or throw a built in one.

Apparently this is an issue that Spark hasn't been able to address for quite a while. But I was able to come up with a work around: https://github.com/perwendel/spark/issues/197#issuecomment-213952246

Basically starting and configuring the embedded Jetty yourself instead of having Spark to do that for you.

For those who want to handle all exceptions and display back the error message, here's a simple way to declare the handler:

exception(Exception.class, exceptionHandler());

and then a simple implementation:

private ExceptionHandler exceptionHandler() {
    return (e, req, res) -> {
        res.status(500);
        res.body("<h1>Exception occurred</h1><div>" + e.getMessage() + "</div>");
    };
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top