12

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);          
        } 
SpringUser
  • 1,351
  • 4
  • 29
  • 59
  • Similar issue here, using @ControllerAdvice. All exceptions we are handling are returning nicely, all that we're not handling, for example, missing required param for endpoint, which spring framework should handle, are returning empty response body, and status code in headers. – Emily Jun 14 '19 at 14:35

3 Answers3

10

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.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
1

This will handle the exceptions raised from within the controller method.

If you send a request for which there is no mapping the controller method will not be invoked at all thus the @ExceptionHandler will be obsolete in that case.

Maybe this article on creating custom handlers may help: article

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
1

Using RequestMapping you can create different responses for every Http code. In this example I show how to control errors and give a response accordingly.

This is the RestController with the service specification

@RestController
public class User {

    @RequestMapping(value="/myapp/user/{id}", method = RequestMethod.GET)
    public ResponseEntity<String> getId(@PathVariable int id){

        if(id>10)
            throw new UserNotFoundException("User not found");

        return ResponseEntity.ok("" + id);
    }

    @ExceptionHandler({UserNotFoundException.class})
    public ResponseEntity<ErrorResponse> notFound(UserNotFoundException ex){

        return new ResponseEntity<ErrorResponse>(
            new ErrorResponse(ex.getMessage(), 404, "The user was not found") , HttpStatus.NOT_FOUND);
    }
}

Within the getId method there is a little logic, if the customerId < 10 It should response the Customer Id as part of the body message but an Exception should be thrown when the customer is bigger than 10 in this case the service should response with an ErrorResponse.

public class ErrorResponse {

    private String message;
    private int code;
    private String moreInfo;

    public ErrorResponse(String message, int code, String moreInfo) {
        super();
        this.message = message;
        this.code = code;
        this.moreInfo = moreInfo;
    }

    public String getMessage() {

        return message;
    }

    public int getCode() {

        return code;
    }

    public String getMoreInfo() {

        return moreInfo;
    }
}

And finally I'm using an specific Exception for a "Not Found" error

public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {
        super(message);
    }
}
ElChava
  • 91
  • 5