我是新手,一般都会对Reactor和反应式编程进行预测.
我目前正在编写一段类似于此的代码:
Mono.just(userId)
.map(repo::findById)
.map(user-> {
if(user == null){
throw new UserNotFoundException();
}
return user;
})
// ... other mappings
Run Code Online (Sandbox Code Playgroud)
这个例子可能很愚蠢,实现这种情况肯定有更好的方法,但重点是:
throw new
在map
块中使用异常是否错误,或者我应该用return Mono.error(new UserNotFoundException())
?替换它?
这两种做法有什么实际区别吗?
我正在尝试将现有的客户端代码替换RestTemplate
为WebClient
. 因此,大多数调用需要阻塞,以便应用程序的主要部分不需要更改。当涉及到错误处理时,这会带来一些问题。有几种情况必须涵盖:
List
成功响应类型匹配的空值为了产生正确的误差 ( Exception
),需要考虑误差响应。到目前为止,我无法接触到错误主体。
我正在使用此RestController
方法来生成错误响应:
@GetMapping("/error/404")
@ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntity error404() {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(new ErrorResponse());
}
Run Code Online (Sandbox Code Playgroud)
使用此响应对象:
public class ErrorResponse {
private String message = "Error message";
public String getMessage() {
return message;
}
}
Run Code Online (Sandbox Code Playgroud)
定义WebClient
如下:
WebClient.builder()
.baseUrl("http://localhost:8081")
.clientConnector(connector)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
Run Code Online (Sandbox Code Playgroud)
连接器的类型为CloseableHttpAsyncClient
(Apache Http client5)。
从我的测试应用程序中,我进行如下调用:
public String …
Run Code Online (Sandbox Code Playgroud)