Use Java Spark after filter to trigger custom actions when 404 occurs

I will try to do it shortly. Here is the problem I am having when trying to understand Spark filters. I am trying to create a simple application, and one of the things that it should do is to create an error report every time the client is about to see an HTTP error, for example. 404 or 500. Here's what my application looks like:

import static spark.Spark.*; public class MyApp { public static void main(String[] args) { get("/hello", (req, res) -> "{\"status\":\"OK\"}"); after((request, response) -> { if (response.raw().getStatus() == 404) { // here run the code that will report the error eg System.out.println("An error has occurred!!"); } }); } } 

For some reason, the response parameter has its status attribute equal to 0 when I check if it is set to 404. The documentation says "after" filters are evaluated after each request and can read the request and read/modify the response , so I have to do it somehow (if only the documents are incorrect).

Basically, I'm trying to catch HTTP errors using the after filter, but when I try to check the response, I don't get what I expect.

Does anyone have an idea what would be another way to do the same or how to make this work?

Thanks.

+5
source share
2 answers

I solved this using wildcard routes. Instead of calling the after method, I added a route for each of the HTTP methods that bind the "*" route.

It is important to have them at the bottom of your Main method, so if the route is not allowed, they always fire.

Here is an example:

 import static spark.Spark.*; public class MyApp { public static void main(String[] args) { get("/hello", (req, res) -> "{\"status\":\"OK\"}"); get("*", (request, response) -> { System.out.println("404 not found!!"); // email me the request details ... ); } } 
+6
source

The preferred way to achieve what you are looking for would be as follows.

 get("/hello", (request, response) -> { // look up your resource using resourceId in request/path/query // oh dear, resource not found throw new NotFoundException(resourceId); }); exception(NotFoundException.class, (e, request, response) -> { response.status(404); response.body(String.format("Resource {%s} not found", e.getResourceId())); // doReporting here. }); public class NotFoundException extends Exception { private final String resourceId; public NotFoundException(String resourceId) { this.resourceId = resourceId; } public String getResourceId() { return resourceId; } } 
+1
source

Source: https://habr.com/ru/post/1207350/


All Articles