Search code examples
javaspringmicroservicesexternalcontext

in a Java MicroServices System where locate the error check?


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?


Solution

  • 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.