Want to handle the exception from only exceptionhandler class of API. Is there any way can remove all the try-catch of the API.
Using the @exceptionhandler but purpose not solved from this approach. Is there any way don't required try catch?
Sure, all you need is a class with a @ControllerAdvice
annotation on top of it, and to make it extends ResponseEntityExceptionHandler
ex:
@ControllerAdvice
public class RestErrorHandler extends ResponseEntityExceptionHandler {
// just for the example but you should probably handle specific exceptions rather than handle 'Exception.class'
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> processError(Exception exception) {
// do something with the exception
return new ResponseEntity<>("Oups", INTERNAL_SERVER_ERROR);
}
...
}
And of course you need to remove the try-catch
or re-throw the exceptions otherwise they wont be catched by the ControllerAdvice
.