Spring反应器中的全局异常处理及相关响应
我正在尝试使用Spring5创建一个web应用程序。这是一项微服务,几乎没有其他微服务受到影响。来自一个服务的响应依赖于另一个。我正在使用全局异常处理我的应用程序 这是我的密码:Spring反应器中的全局异常处理及相关响应,spring,spring-boot,Spring,Spring Boot,我正在尝试使用Spring5创建一个web应用程序。这是一项微服务,几乎没有其他微服务受到影响。来自一个服务的响应依赖于另一个。我正在使用全局异常处理我的应用程序 这是我的密码: @Override public Mono<Response> checkAvailablity(Request request) { Mono<Response> authResponse = userService.authenticateToken(request); re
@Override
public Mono<Response> checkAvailablity(Request request) {
Mono<Response> authResponse = userService.authenticateToken(request);
return authResponse.doOnSuccess(t -> {
// if success is returned.
// Want to return this innerResponse
Mono<Response> innerResponse =
httpService.sendRequest(Constant.SER_BOOKING_SERVICE_CHECK_AVAILABILTY,
request.toString(), Response.class);
}).doOnError(t -> {
logger.info("Subscribing mono in Booking service - On Error");
Mono.error(new CustomException(Constant.EX_MODULE_CONNECTION_TIMED_OUT));
});
基于上述代码,我有两个问题:
在mono中使用了两种方法:flatmap()和onErrorMap() 并更新了我的CheckAvailability()代码:
public Mono-checkavailability(请求){
Mono authResponse=userService.authenticateToken(请求);
返回authResponse.flatmap(t->{
//为成功案例添加了transform()
Mono response=httpService.sendRequest(Constant.SER\u BOOKING\u SERVICE\u CHECK\u availability,
request.toString(),Response.class);
logger.info(“服务预订、服务检查、可用性的响应”);
返回响应;
}).onErrorMap(t->{
//为失败案例添加了onErrorMap()&现在全局异常处理程序中捕获了异常。
抛出新的CustomException(常量.EX\u模块\u连接\u超时);
});
}
在mono中使用了两种方法:flatmap()和onErrorMap()
并更新了我的CheckAvailability()代码:
public Mono-checkavailability(请求){
Mono authResponse=userService.authenticateToken(请求);
返回authResponse.flatmap(t->{
//为成功案例添加了transform()
Mono response=httpService.sendRequest(Constant.SER\u BOOKING\u SERVICE\u CHECK\u availability,
request.toString(),Response.class);
logger.info(“服务预订、服务检查、可用性的响应”);
返回响应;
}).onErrorMap(t->{
//为失败案例添加了onErrorMap()&现在全局异常处理程序中捕获了异常。
抛出新的CustomException(常量.EX\u模块\u连接\u超时);
});
}
@ControllerAdvice
public class ExceptionInterceptor {
public static Logger logger = Logger.getLogger(ExceptionInterceptor.class);
@ExceptionHandler(value = CustomException.class)
@ResponseBody
public Response authenticationFailure(ServerHttpRequest httpRequest, ServerHttpResponse response,
CustomException ex) {
logger.info("CustomException Occured with code => " + ex.getMessage());
return buildErrorResponse(ex.getMessage());
}
public Mono<Response> checkAvailablity(Request request) {
Mono<Response> authResponse = userService.authenticateToken(request);
return authResponse.flatmap(t -> {
// Added transform() for success case
Mono<Response> response = httpService.sendRequest(Constant.SER_BOOKING_SERVICE_CHECK_AVAILABILTY,
request.toString(), Response.class);
logger.info("Response from SER_BOOKING_SERVICE_CHECK_AVAILABILTY");
return response;
}).onErrorMap(t -> {
// Added onErrorMap() for failure case & now exception is caught in global exception handler.
throw new CustomException(Constant.EX_MODULE_CONNECTION_TIMED_OUT);
});
}