0

I need to handle the exceptions in My rest API. I have a layered architecture, composed by Entities, DAOs, Services and controllers. In my services I have the model Exceptions, and I need to know the best way to translate these exceptions to send responses in HTTP. I read about Exception handler and Controller advice but I'm not sure how is the best form to do this. Anyone can iluminate me? Thanks

Samuel Paredes
  • 111
  • 1
  • 10

3 Answers3

1

I would go with @ControllerAdvice for most of the exceptions, for instance, validation error, system errors etc. On the other hand, you could use error handlers for specific cases in your controllers.

This way you have generalized error handler with the possibility to overwrite the default error handling.

Danylo Zatorsky
  • 5,856
  • 2
  • 25
  • 49
0

One way is by the use of spring ExceptionHandler (there are several variants possible depending on spring version).

Some good documentation here

albert_nil
  • 1,648
  • 7
  • 9
-2

best way is to create your own custom exception class and dont handle any excpetion in dao & services instead of just throw custom exception from there and handle all excpetion in controller and response back meaning full message to client from controller.

user2862544
  • 415
  • 3
  • 13
  • this is very opinionated IMHO :p . client should receive meaningful messages when there are errors. For some clients it might be good to receive just the lowlevel original error (mostly on internal network clients), but that's not an option in many other scenarios where you don't want to expose details. For those scenarios, having just a generic exception class and no "intermediate" info (you said to just propagate exception without any intermediate handling) on what happened might mean there is no "business error" that can be sent back. – albert_nil Aug 08 '17 at 18:03