简体   繁体   中英

How to catch Mono error generate one other?

I have a Java 11 Spring Boot application which consumes an external web service which returns 404 when there is no result and I would like it to return 204 in this case.

So, I want to catch 404 errors to raise a 204.

// Before
public UserDto[] getAllUser(String username) {
    return localApiClient.get().uri(baseUrl + username)
            .retrieve()
            .bodyToMono(UserDto[].class)
            .block(REQUEST_TIMEOUT);
}

// what I want
public UserDto[] getAllUser(String username) {
    return localApiClient.get().uri(baseUrl + username)
            .exchangeToMono(response -> {
                if (response.statusCode().equals(HttpStatus.OK)) {
                    return response.bodyToMono(UserDto[].class);
                }
                if (response.statusCode().equals(HttpStatus.NOT_FOUND)) {
                    return response.createException().flatMap(Mono.error(HttpStatus.NO_CONTENT));
                } else {
                    return response.createException().flatMap(Mono::error);
                }
            .block(REQUEST_TIMEOUT);

}

I think there is a better solution but it seems to work

public UserDto[] getAllUser(String username) {
    return localApiClient.get().uri(baseUrl + username)
            .exchangeToMono(response -> {
                    if (response.statusCode().equals(HttpStatus.NOT_FOUND)) {
                        response = ClientResponse.create(HttpStatus.NO_CONTENT).build();
                        return response.bodyToMono(UserDto[].class);
                    }
                    return response.bodyToMono(UserDto[].class);
                })
            .block(REQUEST_TIMEOUT);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM