在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.
答案 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一起使用来序列化对象。 我至少知道两种方法:
您可以定义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);
赞:
@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