【问题标题】:Custom ErrorWebExceptionHandler.handle not being called未调用自定义 ErrorWebExceptionHandler.handle
【发布时间】:2021-03-17 00:30:16
【问题描述】:

我有一个自定义的 ErrorWebExceptionHandler,如下所述:

@Configuration
@Order(-2)
public class GlobalErrorWebExceptionHandler implements ErrorWebExceptionHandler {

    private ObjectMapper objectMapper;
    
    public GlobalErrorWebExceptionHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }
    
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ...
    }
}

虽然正在调用构造函数,但当 API 方法之一抛出异常时,方法 handle 永远不会触发,我仍然可以看到标准输出:

{
    "timestamp": "2021-03-17T00:18:39.033+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "message": "",
    "path": "/my/api/path"
}

是我遗漏了什么还是有更好的方法来全局自定义异常?

【问题讨论】:

    标签: java spring-webflux


    【解决方案1】:

    我最终改变了方法并实现了一个 @ControllerAdvice,类似于下面描述的类:

    @ControllerAdvice
    public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
        
        @ExceptionHandler(value = {WebClientResponseException.class})
        protected ResponseEntity<Object> handleWebClientResponseException(WebClientResponseException ex, WebRequest request) {
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            return handleExceptionInternal(
                ex,
                ex.getResponseBodyAsString(),
                headers,
                ex.getStatusCode(),
                request);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-10
      • 1970-01-01
      • 2015-09-13
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多