This brown bag session was presented by Abdulbasit Kabir.
As developers, we usually build Rest APIs for success in that we clearly define what input(Request) it accepts and the output(Response) to expect. But as anybody who has ever written even a “Hello World!” app knows, code doesn’t always work as it should. So what happens when a client call to your API application results in an error? How do you inform the client what caused the error and how to avoid it beyond just responding with status codes? These are what we’ll cover as done on Distinction.ng back end (JavaEE with Jersey REST API).
Let us look at this scenario.
We have a get question endpoint:
When we try to get a question with an invalid id:
This is not very useful as the response status is 200 but there’s no question because it doesn’t exist. So what if we check if the object is null before it’s returned.
The same API call gives us something… well, ugly and malformed.
Let’s improve the whole application to get an error response which is easier to understand when there’s some sort of error.
After we’re done you’ll get an error response with some details as below.
You’ll first need a custom Exception:
Then create exception mappers for the ApiException and a generic mapper of any Throwable.
Now let’s improve the Question resource so that it takes advantage of the error handling.
And as we saw earlier a request with an id that doesn’t exist: