user1933888
user1933888

Reputation: 3017

Best practice for error handling in Jersey REST API

I have implemented REST API using Jersey 1.9 returning json, till now I did not do any explicit error handling and the framework seem to handle it on its own pretty well.

Now I intend to create an "Application" framework for better error handling, I tried looking for best practices and did not find any

Jersey documentation: https://jersey.java.net/nonav/documentation/1.9/user-guide.html#d4e443

Few search on internet: http://www.codingpedia.org/ama/error-handling-in-rest-api-with-jersey/

But I do not like this as we are just catching all exceptions formatting and rethrowing, I dont see much value with it.

http://howtodoinjava.com/jersey/jax-rs-jersey-custom-exceptions-handling-with-exceptionmapper/ I assume unhandeled exceptions would already be handeled by framework as 500 response code, so dont see the point of above example.

Also I read many discussion about different approaches where even error condition is sent with 200 response but its empty and few people send explicit codes, there does not seem to be a "standard" and that led me to pose this question, seeking best practice from "experts"

Upvotes: 2

Views: 5303

Answers (1)

GuiSim
GuiSim

Reputation: 7559

Communicating errors with end-users is a very important part of API design. I would recommend using the JAX-RS ExceptionMapper mechanism to easily map exceptions to clean error messages.

What I like to do is group all exceptions that can exit the service under two categories.

Client-side exceptions

These exceptions are 100% caused by user input and there is nothing the service can do to avoid them.

Example:

  • Invalid credentials
  • Missing required parameter
  • Invalid JSON body

They should be returned as 4XX error codes with a message clearly explaining the cause of the problem and possibly hinting at a solution.

Server-side exceptions

These exceptions are 100% caused by the current state of your application and there is nothing the client can do to avoid them.

Example:

  • Database is currently down
  • Temporary network issues
  • Application bug

They should be returned as 5XX error codes with a message explaining that there is an issue with the service and that the client should retry later. These are serious issues and need to be resolved quickly.

As your application matures, you'll most likely find ways to avoid resorting to these errors. E.g. by falling back to a read-only mode based on a cache when the database is unavailable.

Other

All other exceptions should be handled in your application logic. If they do not need to be communicated to the end-user, they should not have an ExceptionMapper and should not ever reach the Jersey layer.

Upvotes: 5

Related Questions