在 Enum 中抛出自定义异常,但流没有进入@ExceptionHandler方法

Throwing custom exception inside Enum but flow is not coming to @ExceptionHandler method

提问人:danceAyush 提问时间:6/24/2022 更新时间:6/24/2022 访问量:295

问:

    public enum Metadata{
        AC, CD;
@jsonCreator
public static Metadata get(String value) throw customException
if(!isValid(value)){
throw customException();
}
    }

我的处理程序方法

@ExceptionHandler(customException.class)
public ResponseEntity<Response> handeljsonError(customException e){
return response;
}

当从枚举元数据抛出自定义异常时,流不会出现在自定义处理程序上,而是流将转到 httpMessageNonReadableException,这是其他覆盖方法,因此当我调试其原因时,它显示 ValueInstantiationException。

我希望我的自定义异常方法应该运行而不是 httpMessageNonReadableException

Java 异常 枚举 exceptionhandler uncaughtExceptionHandler

评论


答:

0赞 Arpit Asati 6/24/2022 #1

该类应使用@ControllerAdvice注释扩展 ResponseEntityExceptionHandler。

@ControllerAdvice
public class ControllerAdvisor extends ResponseEntityExceptionHandler 

ResponseEntityExceptionHandler 仅在 HTTP 流中被 spring 调用,请确保您的代码在 HTTP 范围内。

评论

0赞 danceAyush 6/26/2022
是的,它正在扩展 ResponseEntityExceptionHandler
0赞 Arpit Asati 6/26/2022
@danceAyush请求执行时,HTTP 流中会发生此异常?此外,CustomException 类应扩展 RuntimeException。