如何在Spring webflux WebExceptionHandlder

时间:2018-01-01 06:34:31

标签: spring spring-webflux

this post的帮助下,我通过自定义WebExceptionHandler部分在我的Spring 5 WebFlux应用程序中获得了异常处理工作,但是当我想将友好消息中的现有异常转换为客户端时,它确实不行。

我的自定义WebExceptionHandler如下所示,完整代码为here

 WebExchangeBindException cvex = (WebExchangeBindException) ex;
            Map<String, String> errors = new HashMap<>();
            log.debug("errors:" + cvex.getFieldErrors());
            cvex.getFieldErrors().forEach(ev -> errors.put(ev.getField(), ev.getDefaultMessage()));

            log.debug("handled errors::" + errors);
            try {
                DataBuffer db = new DefaultDataBufferFactory().wrap(objectMapper.writeValueAsBytes(errors));
                exchange.getResponse().setStatusCode(HttpStatus.UNPROCESSABLE_ENTITY);
                exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
                exchange.getResponse().writeWith(Mono.just(db));
                return exchange.getResponse().setComplete();

            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return Mono.empty();
            }

状态代码设置正确,但响应内容长度为0.

2 个答案:

答案 0 :(得分:4)

在您的代码示例中,您同时调用:

// write the given data buffer to the response
// and return a Mono that signals when it's done
exchange.getResponse().writeWith(Mono.just(db));
// marks the response as complete and forbids writing to it
exchange.getResponse().setComplete();

由于您正在调用第一个并且没有订阅它,因此没有任何内容写入响应。

您可以将代码更新为:

exchange.getResponse().setStatusCode(HttpStatus.UNPROCESSABLE_ENTITY);
exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF);
return exchange.getResponse().writeWith(Mono.just(db));

答案 1 :(得分:2)

我建议您将标准Spring方式与Codecs一起使用来序列化对象。 我至少知道两种方法:

  1. 使用ServerCodecConfigurer类和EntityResponse对象。

您可以定义ServerCodecConfigurer @Bean

@Bean
public ServerCodecConfigurer serverCodecConfigurer() {
    return new DefaultServerCodecConfigurer();
}

并在类似这样的util方法中使用它

public class ResponseUtil {

    @NotNull
    public static <T> Mono<Void> putResponseIntoWebExchange(ServerWebExchange exchange, ServerCodecConfigurer serverCodecConfigurer, Mono<EntityResponse<T>> responseMono) {

        return responseMono.flatMap(entityResponse ->
                entityResponse.writeTo(exchange, new ServerResponse.Context() {
                    @NotNull
                    @Override
                    public List<HttpMessageWriter<?>> messageWriters() {
                        return serverCodecConfigurer.getWriters();
                    }

                    @NotNull
                    @Override
                    public List<ViewResolver> viewResolvers() {
                        return Collections.emptyList();
                    }
                }));
    }

}

您的代码将如下所示

        WebExchangeBindException cvex = (WebExchangeBindException) ex;
        Errors errors = new Errors();//Class wrapper for Map with errors
        log.debug("errors:" + cvex.getFieldErrors());
        cvex.getFieldErrors().forEach(ev -> errors.put(ev.getField(), ev.getDefaultMessage()));

        log.debug("handled errors::" + errors);

        final Mono<EntityResponse<Errors>> responseMono = EntityResponse.fromObject(errors)
            .status(HttpStatus.UNPROCESSABLE_ENTITY)
            .contentType(APPLICATION_JSON)
            .build();

        return ResponseUtil.putResponseIntoWebExchange(exchange, serverCodecConfigurer, responseMono);
  1. 使用标准方式进行错误处理。 默认情况下,Spring WebFlux使用DefaultErrorAttributes类来处理所有异常。您可以通过覆盖此类并在Spring上下文中定义该类的bean来简单地对其进行自定义。

赞:

@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        final Map<String, Object> errorAttributes = super.getErrorAttributes(request, includeStackTrace);

        Throwable error = getError(request);

        //Depends of error add or replace errorAttributes with your custom message, http status, etc
        if (error instanceof WebExchangeBindException) {
            errorAttributes.put("message", error.getMessage());

            Errors errors = new Errors();
            error.getFieldErrors().forEach(ev -> errors.put(ev.getField(), ev.getDefaultMessage()));

            errorAttributes.put("errors", error);
        }

        return errorAttributes;
    }

}

这是在Spring WebFlux中处理异常的更原始的方式。 有一篇很好的帖子-https://dzone.com/articles/exception-handling-in-spring-boot-webflux-reactive