如何在WebClient中正确获取自定义错误正文消息



我试图实现的是用404代码获得响应错误,用WebClient获得错误主体,我该如何正确地做到这一点?

这是我的错误代码404的响应和来自另一个API的主体响应:

{
"timestamp": "2020-09-02T07:36:01.960+00:00",
"message": "Data not found!",
"details": "uri=/api/partnershipment/view"
}

下面是我的消费代码的样子:

Map<String,Long> req = new HashMap<String,Long>();
req.put("id", 2L);
PartnerShipmentDto test = webClient.post()
.uri(urlTest).body(Mono.just(req), PartnerShipmentDto.class)
.exchange()
.flatMap(res -> {
if(res.statusCode().isError()){
res.body((clientHttpResponse, context) -> {
throw new ResourceNotFound(clientHttpResponse.getBody().toString());
});
throw new ResourceNotFound("aaaa");
} else {
return res.bodyToMono(PartnerShipmentDto.class);
}
})
.block();

这是我的ResourNotFound.java类:

@SuppressWarnings("serial")
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFound extends RuntimeException {

public ResourceNotFound(String message){
super(message);
}

}

这是我使用@ControllerAdvice:的全局异常处理程序

@ControllerAdvice
@RestController
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public final ResponseEntity<Object> handleAllException(Exception ex, WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
logger.error(ex.getMessage());
return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(ResourceNotFound.class)
public final ResponseEntity<Object> handleResourceNotFoundException(ResourceNotFound ex, WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
logger.error(ex.getMessage());
return new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND);
}
}

但是我在ResourceNotFound异常中得到的响应是这样的(这是我在消费者端的错误(:

{
"timestamp": "2020-09-02T07:50:48.132+00:00",
"message": "FluxMap",
"details": "uri=/api/shipmentaddressgrouping/store"
}

它写着";FluxMap";只是,我如何得到";消息";领域我想得到";时间戳";以及";细节";字段太

您给出的示例代码的主要问题是以下代码行

throw new ResourceNotFound(clientHttpResponse.getBody().toString());

它的类型是Flux<DataBuffer>,而不是实际的响应体。这导致了您所看到的问题。

解决这个问题的方法是在错误响应体上调用bodyToMono方法,并映射到一个java对象。这可以通过从web客户端公开的onStatus操作符来完成,该操作符允许您对特定状态代码执行特定操作。

下面的代码片段应该可以解决这个

webClient.post()
.uri(uriTest).body(Mono.just(req), PartnerShipmentDto.class)
.retrieve()
.onStatus(HttpStatus::isError, res -> res.bodyToMono(ErrorBody.class)
.onErrorResume(e -> Mono.error(new ResourceNotFound("aaaa")))
.flatMap(errorBody -> Mono.error(new ResourceNotFound(errorBody.getMessage())))
)
.bodyToMono(PartnerShipmentDto.class)
.block();

ErrorBody应该包含要从json映射到java对象的所有字段。下面的例子仅将";消息";领域

public class ErrorBody {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

相关内容

  • 没有找到相关文章

最新更新