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";
}
});
For those who want to handle all exceptions and display back the error message, here's a simple way to declare the handler:
and then a simple implementation:
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.
Try to use this tip below
Add these lines right after last route because Spark cares about order
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.
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.
In Spark 2.3 documentation:
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.