Search code examples
javaspringspring-bootexceptionexceptionhandler

Remove try catch and handle the exception using exceptionhandler in rest api service using Spring Boot


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?


Solution

  • 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.

    see: https://docs.spring.io/spring-framework/docs/6.1.2/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html