-2

I have a controller that receives a request, passes the data to the service and the service makes an external http call, the answer is returned to the service and then the controller returns a web page.

An error message or an exception could come from the external call.

Should the error check be done in the service that makes the external call or in the controller before returning the web page?

Vito Lipari
  • 795
  • 8
  • 35

2 Answers2

1

I am sorry to say that it is totally up to you. You could catch the error at the HTTP calling method, or you catch everything at your controller level if you prefer a more global catch.

If you are using Spring, I would have a look at the ControllerAdvice class and implement my catches there for the different type of errors: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

@ControllerAdvice
class GlobalControllerExceptionHandler {
    @ResponseStatus(HttpStatus.CONFLICT)  // 409
    @ExceptionHandler(DataIntegrityViolationException.class)
    public void handleConflict() {
        // Nothing to do
    }
}
CharlieNoodles
  • 316
  • 2
  • 9
1

Catch an exception for good only in places where you know a specific, plausible way how to continue, and at application top level (which doesn't exist if you implement a service to be used by another application).

When you receive an error response from an external call, make sure to treat it like an exception, e.g. by creating and throwing an exception.

Otherwise just make sure that your caller gets the appropriate failure information:

  • Within one JVM just let the exception bubble up.
  • Avoid wrapping exceptions as much as possible, so your caller has the chance to easily see what really happened without unwrapping multiple layers of exception wrappers, and also to spare yourself from lots of unproductive code.
  • At JVM borders, convert the exception to an appropriate error message (e.g. 4xx or 5xx HTTP status).
  • Before you're sending an error response to your client, log the error. Your client's log (if it exists at all) won't contain all information about the problem, and most probably won't be available to you.
Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7