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 code404 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 with500 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?