Seems like overkill to create 300 errors for 300 exceptions. What I did was create our own HttpErrorException
class that contains the HTTP error we would like to return. Developers were advised to throw one of those when they encountered an exception or an error. If an exception bubbled up that was not one of the new HttpErrorExceptions
, then a 500 is returned. We did not convert other exceptions into HTTP errors because I felt it is wrong to assume that each occurrence of a particular Exception will always map back to a particular HTTP error. The reason for this is because there are a lot of dependencies (other libraries we are using) and they might throw any type of exception which for any particular situation might not map back nicely to the HTTP error we had in mind. So I rather be explicit.
Here is a contrite example of a typical usage.
Account getAccount(String id){
Account a = null;
try{
a = accountRepo.findById(id);
catch(Exception e) {
String error = "Got exception while trying to get Account from db.";
logger.(error, e);
throw new HttpErrorException(500, error);
//or throw new HttpErrorException(HttpStatus.INTERNAL_SERVER_ERROR, error);
}
throw404IfNull(a);
return a;
}
The throwIf404IfNull
is just a simple method we created to reduce if
statements in our code. We have several of these methods and our code stays free of if
statements that otherwise would get unit tested.
void throw404IfNull(Object obj){
if(obj == null) {
throw new HttpErrorException(400, "Object was not found");
}
}
We use Spring's exception handling capabilities to map all HttpErrorException
's to a nice well formatted HTTP error with the error status that is in the exception.