1

I have a @ControllerAdvice class which captures various types of custom Exceptions. The problem is, these custom exceptions can be thrown my various methods within the Controller.

So in my @ControllerAdvice class, when it's time to Splunk the Exception, I need to know what specific action was going on, in order to put the proper code in my Splunk log.

For example:

@RestController
@RequestMapping(value = "/person/{id}")
public class PersonController {

public ResponseEntity<PersonDto> getPerson(@PathVariable final String id) throws PersonNotFoundException {

public ResponseEntity<PersonStuffDto> getPersonStuff(@PathVariable final String id) throws PersonNotFoundException {

... and my advice:

@ControllerAdvice
public class PersonControllerExceptionHandler {

  @ExceptionHandler(PersonNotFoundException.class)
  @ResponseStatus(HttpStatus.UNAUTHORIZED) @ResponseBody
  public ErrorResponse personNotFoundException (final  PersonNotFoundException exception, final HttpServletRequest request) {
      ... Splunk ...
  }

Within the personNotFoundException() method, I need to Splunk either "RETRIEVING_PERSON" code, or a "RETRIEVING_PERSON_STUFF" code.

How can I distinguish the source of the Exception? Do I have to inspect the request ... look at the url or something? And if so ... woudldn't it just be easier to leave the Exception handling, or at least this part of it, in the Controller itself?

Robert Bowen
  • 487
  • 2
  • 13
  • 24
  • why you would want to distinguish between the calling method as you are throwing the same exception and catching it in a common implementation? Either throw different exception or handle them in the controller. – kk. Jun 13 '17 at 11:07
  • I get what you're saying. It's just that, both methods do a look-up of Person. One to return the Person itself, the other to return that Person's Stuff. So while the Exception -- PersonNotFoundException -- is the same, I need to log _where_ it happened. Hence my question. – Robert Bowen Jun 13 '17 at 11:48

1 Answers1

2

you can do one of this:

  1. add exception reason (and description if it's necessary) in PersonNotFoundException as optional field.you can put source via code or description.

  2. create two sub exception from PersonNotFoundException and in exception controller resolve by exception type. Throw appropriate sub type of PersonNotFoundException

preferably 1 variant as you shouldn't create new classes(exception).

Error codes within exception vs exceptions hierarhy

and

6 Tips to Improve Your Exception Handling

xyz
  • 5,228
  • 2
  • 26
  • 35
  • (1) looks like the best way to go. Now I just need to change the code to add the source somewhere ... code is already used .. description .. don't know, I think I may add a field ... Thanks! – Robert Bowen Jun 13 '17 at 11:51