6

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";
   }
});
dns
  • 2,753
  • 1
  • 26
  • 33

7 Answers7

4

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.

Ken Block
  • 3,423
  • 1
  • 21
  • 23
  • Error:(214, 35) java: lambda expressions are not supported in -source 1.6 (use -source 8 or higher to enable lambda expressions) – dns Oct 25 '15 at 19:46
  • When I change target to 8, it returns: Error:java: javacTask: source release 8 requires target release 1.8 – dns Oct 25 '15 at 19:48
  • Do I've to re-build all external dependency (such as Jetty, servlet, freemarker, slf4j, spark-core) to 1.8 ? – dns Oct 25 '15 at 20:00
  • can you tell me your IDE and Build Tool which you used? – Ken Block Oct 26 '15 at 03:00
3

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>");
    };
}
Daniel Seltzer
  • 126
  • 1
  • 4
2

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>
janickr
  • 41
  • 3
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>");
abhinav pandey
  • 574
  • 2
  • 8
  • 21
  • Thanks. It has been 5 years. Spark developer seems to be very slow to fix this basic unimplemented feature. There's also other unimplemented basic HTTP specification that Spark developer decide to ignore it. – dns Apr 14 '18 at 05:37
  • This method accepts a Route too, in case you want to set the content type: `notFound((req, res) -> ...)` – z0r Sep 06 '19 at 06:46
1

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");
        }
    }
 });
Shekhar
  • 109
  • 3
  • the problem is the 'public directory'. It's imposible to filter every url path because public dir (which throw Jetty 404 error page). – dns Apr 07 '14 at 15:57
1

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.

1

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.

  • Please add the relevant code here in your question. If you happen to delete your github, the answer becomes useless :) – Alfabravo Apr 13 '18 at 18:51