SparkJava custom error page
Asked Answered
S

7

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";
   }
});
Savina answered 1/11, 2013 at 16:47 Comment(0)
D
3

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>");
Deserving answered 13/4, 2018 at 18:47 Comment(2)
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.Savina
This method accepts a Route too, in case you want to set the content type: notFound((req, res) -> ...)Solicitor
F
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.

Farnesol answered 16/10, 2015 at 20:12 Comment(4)
Error:(214, 35) java: lambda expressions are not supported in -source 1.6 (use -source 8 or higher to enable lambda expressions)Savina
When I change target to 8, it returns: Error:java: javacTask: source release 8 requires target release 1.8Savina
Do I've to re-build all external dependency (such as Jetty, servlet, freemarker, slf4j, spark-core) to 1.8 ?Savina
can you tell me your IDE and Build Tool which you used?Farnesol
L
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>");
    };
}
Loft answered 30/11, 2016 at 17:10 Comment(0)
D
3

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>");
Deserving answered 13/4, 2018 at 18:47 Comment(2)
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.Savina
This method accepts a Route too, in case you want to set the content type: notFound((req, res) -> ...)Solicitor
S
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>
Secretary answered 14/12, 2013 at 23:37 Comment(0)
Y
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");
        }
    }
 });
Yachtsman answered 5/4, 2014 at 5:11 Comment(1)
the problem is the 'public directory'. It's imposible to filter every url path because public dir (which throw Jetty 404 error page).Savina
E
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.

Enolaenormity answered 28/10, 2015 at 20:19 Comment(0)
C
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.

Chanticleer answered 24/4, 2016 at 13:4 Comment(1)
Please add the relevant code here in your question. If you happen to delete your github, the answer becomes useless :)Centesimo

© 2022 - 2024 — McMap. All rights reserved.