Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SparkJava custom error page

Tags:

spark-java

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";
   }
});
like image 430
dns Avatar asked Nov 01 '13 16:11

dns


2 Answers

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.

like image 106
Ken Block Avatar answered Sep 30 '22 15:09

Ken Block


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>");
like image 43
abhinav pandey Avatar answered Sep 30 '22 16:09

abhinav pandey