[英]Java - Webclient - Return custom entity response when exception occurs
I want to return a custom entity response when a specific exception occurs (Example, Unauthorized exception).我想在发生特定异常时返回自定义实体响应(例如,未经授权的异常)。 I know how to catch it but only to return a custom exception;
我知道如何捕获它,但只返回一个自定义异常;
public Mono<ResponseEntity<MagentoAdobeOrderResponse>> getOrder(String orderId, String token){
return webClient.get()
.uri(orderUrl+"/"+orderId)
.header(HttpHeaders.CACHE_CONTROL, "no-cache")
.header(HttpHeaders.ACCEPT, "*/*")
.header(HttpHeaders.ACCEPT_ENCODING, "deflate, br")
.header(HttpHeaders.CONNECTION, "keep-alive")
.header(HttpHeaders.AUTHORIZATION, "Bearer "+token)
.retrieve()
.toEntity(MagentoAdobeOrderResponse.class);
.onErrorMap(Unauthorized.class, ex -> new AdobeMagentoUnauthorizedException(String.valueOf(HttpStatus.UNAUTHORIZED.value()),
ButttonMilesConstants.BANK_PROBLEMS_ERROR_MESSAGE));
}
What I want is something like this:我想要的是这样的:
public Mono<ResponseEntity<MagentoAdobeOrderResponse>> getOrder(String orderId, String token){
return webClient.get()
.uri(orderUrl+"/"+orderId)
.header(HttpHeaders.CACHE_CONTROL, "no-cache")
.header(HttpHeaders.ACCEPT, "*/*")
.header(HttpHeaders.ACCEPT_ENCODING, "deflate, br")
.header(HttpHeaders.CONNECTION, "keep-alive")
.header(HttpHeaders.AUTHORIZATION, "Bearer "+token)
.retrieve()
.toEntity(MagentoAdobeOrderResponse.class);
.onErrorMap(Unauthorized.class, return new ResponseEntity<MagentoAdobeOrderResponse>());
}
it's possible?这是可能的?
Regards问候
You can catch your exception in a class annotated with @ControllerAdvice
and then return your custom entity response.您可以在带有
@ControllerAdvice
注释的 class 中捕获您的异常,然后返回您的自定义实体响应。 A @ControllerAdvice
class can help you handle exceptions thrown by your application. @ControllerAdvice
class 可以帮助您处理应用程序抛出的异常。
Something that might look like what you want to do:可能看起来像您想做的事情:
@ControllerAdvice
public class ControllerAdviceResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {AdobeMagentoUnauthorizedException.class})
protected ResponseEntity<Object> handleAdobeMagentoUnauthorizedException(
RuntimeException exception,
ServletWebRequest request
) {
MagentoAdobeOrderResponse response = new MagentoAdobeOrderResponse();
return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.