0

I'm developing a microservice using Dropwizard (Jersey as JAX-RS implementation + Jetty as a web server) and Spring JdbcTemplate. In order to provide users of my API proper responses I'm trying to find out the best way to handle exceptions which are thrown at DAO layer.

There are a few particular points of interest for me:

  • EmptyResultDataAccessException is thrown by JdbcTemplate#queryForObject method if entity with given id is not found.

    I catch this exception id my DAO and just return null, which is thransformed into response with status code 404 Not Found in API layer.

  • DataIntegrityViolationException is thrown when an attempt to insert
    or update data results in violation of an integrity constraint.

    I wrap it in my custom checked exception and rethrow in catch clause. Then this dao layer exception is caught in my service layer (and once more in catch clause I throw my custom service layer exception). Then in my API layer I catch service layer exception, log it and return response with 409 Conflict status code.

  • DataAccessException is the superclass for all JdbcTemplate (unchecked) exceptions. I catch this exception and wrap in my my custom exception (which is at the end caught at my API layer). Then I return response with 500 Internal Server Error status code.

In this way I want to differentiate 4xx and 5xx errors. If i don't catch JdbcTemplate unchecked exceptions the will bubble up to servlet and the users will always receive 500 Internal Server Error, which is not good. Another way is to catch all JdbcTemplate exceptions with implementations of ExceptionMapper<T> interface in my API module. But in this case I will have tightly coupled code and changes in my DAO layer implementation will lead to changes in API layer.

So my question is - is it good enought to use the approach I've discribed?

  • You should use ExceptionMappers http://stackoverflow.com/a/39037036/2588800 – Svetlin Zarev Mar 19 '17 at 12:02
  • Than changes in DAO layer will force me to make changes in API layer. I will have to write new mappers. – Kostyantyn Panchenko Mar 19 '17 at 13:29
  • Check here: http://www.codingpedia.org/ama/error-handling-in-rest-api-with-jersey/ for ideas. You need 2 mappers only: one for the unchecked exceptions which returns JSON response with HTTP 500 error code and the other catches your checked exceptions (all extending some base exception) giving them the desired HTTP error code according to the particular exception (400, 402, etc), some description and probably some hint. – zloster Mar 21 '17 at 18:16

0 Answers0