0

I am working with microservices architecture in Java using Spring Boot. I am very new to it and I wonder if for example I can't get answer for service that I am calling, if http client/server error is returned should we log or throw exception?

user9347049
  • 1,927
  • 3
  • 27
  • 66
  • Because I am kinda more familiar with RestTemplate. That's why I choose it :) Any advices what should I do regarding my code and question? – user9347049 Aug 20 '21 at 08:26

2 Answers2

0

You should do both:

  • Tell to your client that an error occured
  • Log the error for maintenance purpose

A way to go for the first point is to centralize error handling in one place, you can use for that a @RestControllerAdvice annotated class.

akuma8
  • 4,160
  • 5
  • 46
  • 82
  • I dont have a controller here and I should display an error here in service that is calling server. So client should throw an error if no data is provided or the timeout exception. Also, how should I do it form my code? I have updated my question. Please take a look – user9347049 Aug 20 '21 at 08:25
  • That does not prevent you to add a controller advice to handle all your exceptions. Take a look at how ControllerAdvice works. You can also add a generic way to handle your exceptions by adding a class which would contain the error code, the message, the date, etc... and return an instance of that class (in the controller advice) when an exception occures. So in you `catch` block you could throw a generic exception which would be catched by the controller advice. – akuma8 Aug 20 '21 at 08:39
  • Yes, that is true. So you advise me to create a class for example `ApplicationExceptionHandler` annotated with `@RestControllerAdvice`and there create some custom methods to call which generate different error handlings? – user9347049 Aug 20 '21 at 08:51
  • Yes that’s it. You should also gentrify as much as possible your exceptions and their handling. Does not try to create an type of exception for each case, it will be really tedious to maintain. – akuma8 Aug 20 '21 at 08:59
0

I advise you to do both.

If there is a fallback response in case of failure of downstream API call?

Yes: send that response along with logging the error.

No: log the error and send the appropriate response to the client along with the response code and message.

I suggest to have a generic API error response which should send valid reponse code along with http status code.

Pramod
  • 1,376
  • 12
  • 21
  • Hi thank you for your answer. I now realize I should do both. But how should I do it form my code? I have updated my question. Please take a look – user9347049 Aug 20 '21 at 08:23
  • @user9347049 you can refer to https://stackoverflow.com/questions/42993428/throw-exception-in-optional-in-java8/42993594 to understand error handling in optional. – Pramod Aug 20 '21 at 10:13