During the development of a small web API, we decided to separate internal exceptions from public exceptions. Public exceptions are HTTP exceptions, that translate into HTTP responses with proper status code (e.g: BadRequestHttpException, NotFoundHttpException, etc). Internal exceptions are either exceptions thrown from adapters in our system (cache layer, persistence layer, etc.) or the domain (InvalidUserException, BadPasswordException, etc.).
This has been great so far. However, our controllers are starting to smell really bad:
try {
securityService.login(credentials);
} catch (InvalidOAuthProviderException e) {
throw new BadRequestHttpException(e.getMessage(), e.getCode());
} catch (UserNotFoundException e) {
throw new NotFoundHttpException(e.getMessage(), e.getCode());
} catch (InactiveUserException e) {
throw new NotFoundHttpException(e.getMessage(), e.getCode());
} catch (InvalidOAuthTokenException e) {
throw new ForbiddenHttpException(e.getMessage(), e.getCode());
}
The HttpException constructor signature is the error message and code. This will result in a JSON body: {"message":"","code":222}. The code is the unique error code for doc reference. The actual response HTTP code is defined by the type of the exception.
This is clearly not a good sign and i'm sure there's something wrong in the design here. Any help?