简体   繁体   English

使用 @ExceptionHandler 处理自定义异常

[英]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.我有一个 class 使用 Spring 注释 @ExceptionHandler 来捕获异常,这个 class 也支持一些自定义异常。 I would like that when I raise the exception CustomRuntimeException in this way throw new CustomRuntimeException(args...);我希望当我以这种方式引发异常CustomRuntimeExceptionthrow 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.正如public Elias 在评论中提到的那样, protected应该考虑到该方法。

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.顺便说一句,无需在方法中添加@ResponseBody注释。

Try using @ControllerAdvice and make sure @ControllerAdvice annotated class is within package of component scan.尝试使用@ControllerAdvice并确保@ControllerAdvice注释的 class 在组件扫描的 package 内。

There are other ways to achieve custom exceptions handling in spring boot — please see referenced link below.还有其他方法可以在 spring 引导中实现自定义异常处理 - 请参阅下面的参考链接。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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