Java – how to handle exceptions of multiple routes
•
Java
I'm mastering the spark framework, and I'm trying to understand the best way to handle exceptions in multiple paths
At present, I have many routes that handle exceptions in the following ways:
...
catch (final Exception e) {
...
response.status(418);
return e.getMessage();
}
...
This leaves many shortcomings, mainly the repetition of exception logic between them I know it can be improved by refactoring, but I want to know if there is an exception handler mechanism similar to that in spring. You can perform an action when throwing a specific exception, for example:
@ExceptionHandler(Exception.class)
public void handleException(final Exception e,final HttpServletRequest request) {
...executed for the matching exception...
}
So, is there a spark esque mechanism for exception handling? I have checked the document and made it brief If not, I will continue my refactoring plan thank you.
Solution
You can handle exceptions like this:
get("/throwexception",(request,response) -> {
throw new NotFoundException();
});
exception(NotFoundException.class,(e,request,response) -> {
response.status(404);
response.body("Resource not found");
});
Examples obtained from spark docs
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
