Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions for multiple Route

I'm getting to grips with the Spark Framework and I'm trying to understand the best way of handling exceptions in a uniform way for multiple Routes.

At the moment I have a number of Routes which all handle exceptions along the lines of:

...
catch (final Exception e) {
    ...
    response.status(418);
    return e.getMessage();
}
...

This leaves a lot to be desired, mainly the exception logic is duplicated between them. I know that it can be improved by refactoring but I was wondering if there's something similar to the ExceptionHandler mechanism in Spring where you can perform an action when a particular exception is thrown, e.g.:

@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've checked the documentation and come up short. If there isn't, I'll go ahead with my refactoring plans. Thanks.

like image 934
Jonathan Avatar asked Nov 28 '12 12:11

Jonathan


People also ask

How do you handle exceptions on a camel route?

Using onException to handle known exceptions is a very powerful feature in Camel. You can mark the exception as being handled with the handle DSL, so the caller will not receive the caused exception as a response. The handle is a Predicate that is overloaded to accept three types of parameters: Boolean.

How do you handle different exceptions?

The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.

Can we throw multiple exceptions?

You can't throw two exceptions. I.e. you can't do something like: try { throw new IllegalArgumentException(), new NullPointerException(); } catch (IllegalArgumentException iae) { // ... }

How do you handle exceptions without catching?

throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.


1 Answers

You can handle exceptions like so:

get("/throwexception", (request, response) -> {
    throw new NotFoundException();
});

exception(NotFoundException.class, (e, request, response) -> {
    response.status(404);
    response.body("Resource not found");
});

Example taken from the Spark docs.

like image 76
Pixel Elephant Avatar answered Sep 21 '22 13:09

Pixel Elephant