简体   繁体   中英

Handle custom exceptions using @ExceptionHandler

I have a class that catches exceptions using the Spring annotation @ExceptionHandler and this class support some custom exceptions as well. I would like that when I raise the exception CustomRuntimeException in this way throw new CustomRuntimeException(args...); , it will be caught and handled in the following method:

@ControllerAdvice
public class CutomExceptionManager {

    // code
    
    @ExceptionHandler({CustomRuntimeException.class})
    @ResponseBody
    private ResponseEntity<ErrorResource> handleCustomException(CustomException e, HttpServletRequest request, HttpServletResponse response) {
        logger.error("unhandled exception: ", (Exception)e);
        
        // other code
    }
    
}

This doesn't work.

As mentioned in the comments by @Tom Elias, the method should be protected or public to be taken in account by Spring.

As an example, the following code is working.

@ExceptionHandler(ControllerException.class)
public ResponseEntity<ControllerException> handleControllerException(ControllerException controllerException) {
    log.error(controllerException.getFullMessage(), controllerException);
    return new ResponseEntity<>(controllerException, HttpStatus.valueOf(controllerException.getStatus()));
}

BTW, no need to add the @ResponseBody annotation to the method.

Try using @ControllerAdvice and make sure @ControllerAdvice annotated class is within package of component scan.

There are other ways to achieve custom exceptions handling in spring boot — please see referenced link below.

https://www.baeldung.com/exception-handling-for-rest-with-spring

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