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?
ResponseEntity<Foo>
orResponseEntity<Bar>
. You can create one Error entity and return it like ResponseEntity<Error>.