2

How do I configure a single rest controller to handle exceptions for different API calls returning different object types?

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Foo> method1() 

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Bar> method2()

Let's say both method1() and method2() throws an instance of MyException, then I need to handle them differently the following way:

@ExceptionHandler(MyException.class)
@ResponseBody
public ResponseEntity<Foo> handleFoo(Exception ex) {
    //Return foo with error description
    Foo f = new Foo();
    f.setError(ex.getMessage());
    //Set f to response entity
    return new ResponseEntity<>(); 
}

@ExceptionHandler(MyException.class)
@ResponseBody
public ResponseEntity<Bar> handleBar(Exception ex) {
     //Return bar with error description
    Bar b = new Bar();
    b.setError(ex.getMessage());
    //Set b to response entity
    return new ResponseEntity<>(); 
}

When method1() throws an instance of MyException, then handleFoo() should be called. And for method2(), handleBar() should be called.

Is this possible in a single Rest controller or do I need 2 rest controllers for each method?

2
  • In case of exception you don't have to return ResponseEntity<Foo> or ResponseEntity<Bar>. You can create one Error entity and return it like ResponseEntity<Error>. Commented Sep 7, 2016 at 17:13
  • otherwise you throw 2 different exception in each scenario, it is not possible
    – kuhajeyan
    Commented Sep 7, 2016 at 17:18

1 Answer 1

1

The advantage of @ExceptionHandler is that you can have the same exception from multiple places handled in a single place. You're looking for the opposite: handling an exception in multiple places/ways.

You can't achieve that within a single class and the annotation, but you can do it with a normal try/catch in method1() and method2().

1
  • I tried adding a new method (say method2()) to an existing controller and use the same exception handling logic for it. I agree with what you said. Commented Sep 7, 2016 at 23:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.