简体   繁体   中英

@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);          
        } 

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.

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

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM