提问人:Konrad Groń 提问时间:10/31/2023 最后编辑:ahuemmerKonrad Groń 更新时间:11/6/2023 访问量:27
为什么在 Spring Reactor 中使用 WebClient 时 SwitchIfEmpty 不起作用
Why SwitchIfEmpty not working when i use WebClient in Spring Reactor
问:
控制器:
@PostMapping("/login")
public Mono<ResponseEntity<String>> logIn(@RequestBody @Valid Mono<LoginAndPasswordData> user) {
return authenticationUserPort.logIn(user).flatMap(convertObjectToJsonResponse::convert);
}
服务:
public Mono<Result<IsCorrectCredentials>> logIn(Mono<LoginAndPasswordData> userLoginDataMono) {
return userLoginDataMono.flatMap(userLoginData ->
userRepositoryPort.findUserWithEmail(userLoginData.login())
.flatMap(userFromDb -> {
if (hashPasswordPort.checkPassword(userLoginData.password(),
userFromDb.password())) {
return Mono.just(Result.<IsCorrectCredentials>success(new IsCorrectCredentials(true)));
} else {
return Mono.just(Result.<IsCorrectCredentials>success(new IsCorrectCredentials(false)));
}
}).switchIfEmpty(
Mono.just(Result.IsCorrectCredentials>error(ErrorMessage.USER_NOT_FOUND
.getMessage()))))
.onErrorResume(ex -> Mono.just(
Result.IsCorrectCredentials>error(ErrorMessage.RESPONSE_NOT_AVAILABLE
.getMessage())));
}
当我将 Postman 与不存在的用户一起使用时,一切正常。例如;
数据:
{
"login":"noExistsUser",
"password":"example"
}
结果:
{
"ErrorMessage": " User not found "
}
但是当我使用 WebClient 请求时:
@Override
public Mono<ResponseEntity<String>> isCorrectCredentials(Mono<LoginAndPasswordData> loginAndPasswordData) {
Mono<ResponseEntity<String>> result = WebClient.create().post()
.uri(uri)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromPublisher(loginAndPasswordData, LoginAndPasswordData.class))
.retrieve()
.toEntity(String.class)
.map(responseEntity -> new ResponseEntity<>(responseEntity.getBody(), responseEntity.getHeaders(), responseEntity.getStatusCode()));
return result;
}
当用户存在时,响应是OK,但是当数据库中不存在用户时,我从webclient得到以下响应:
{
"timestamp": "2023-10-30T20:56:09.878+00:00",
"path": "/login",
"status": 500,
"error": "Internal Server Error",
"requestId": "7273059f-30"
}
和内部例外:
400 Bad Request from POST http://localhost:8082/authentication/login
这看起来像是逻辑错误。switchIfEmpty
答: 暂无答案
评论