Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ExceptionHandler(Exception.class) not handling all types of exceptions

I am trying to handle all Types of exceptions using @ExceptionHandler(Exception.class). But it's not handling all types of exception.

When I am trying to access wrong HTTP method from postman/ browser I am not getting any response blank page is coming.

Can please any one tell me why I am not getting any response or tell me if I am doing something wrong in my code?

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ControllerAdvice
    public class RestExceptionHandler extends ResponseEntityExceptionHandler {


        @ExceptionHandler(Exception.class)
        public ResponseEntity<ExceptionMessage> handleAllExceptionMethod(Exception ex,WebRequest requset,HttpServletResponse res) {


            ExceptionMessage exceptionMessageObj = new ExceptionMessage();

            exceptionMessageObj.setStatus(res.getStatus());
            exceptionMessageObj.setError(ex.getLocalizedMessage());     
            exceptionMessageObj.setException(ex.getClass().getCanonicalName());
            exceptionMessageObj.setPath(((ServletWebRequest) requset).getRequest().getServletPath());  

            return new ResponseEntity<ExceptionMessage>(exceptionMessageObj, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);          
        } 
like image 971
SpringUser Avatar asked Jun 06 '18 14:06

SpringUser


1 Answers

Either override ResponseEntityExceptionHandler#handleExceptionInternal()or don't extend ResponseEntityExceptionHandler.

@Order(Ordered.HIGHEST_PRECEDENCE) on a @ControllerAdvice should work before ResponseEntityExceptionHandler is invoked as per this answer which suggests that Spring Framework 4.3.7 is needed.

like image 95
Karol Dowbecki Avatar answered Oct 05 '22 04:10

Karol Dowbecki