Search code examples
spring-bootreactive-programmingspring-webfluxproject-reactor

How to properly return HttpStatus in Mono<ResponseEntity>?


I have an api which returns some HttpStatus code. And based on the code the gatekeeper will perform some action. Following is just a skeleton of the API.

@GetMapping("/globalretry")
public Mono<ResponseEntity> testGlobalRetryFilter(@RequestParam(name = "code") int code) {
    Map<String, Object> map = new LinkedHashMap<>();
    map.put("code", code);
    switch (code) {
        case 200:
            map.put("status", "SUCCESS");
            break;
        case 504:
            map.put("status", "RETRY: GATEWAY_TIMEOUT");
            break;
        default:
            map.put("status", "BAD_REQUEST");
            break;
    }
    return Mono.just(new ResponseEntity(map, HttpStatus.valueOf(code)));
}

Now the problem is , if I return the response code in such way, then spring is not able to identify the status code from Mono<ResponseEntity>. Can any body help me on how to return the statuscode in a way thus spring can identify the response's status code


Solution

  • You can create your own object plus in construct you have too add HTTP_STATUS example:

    new ResponseEntity<>(new ErrorResponse(HttpStatus.BAD_REQUEST, LOGIN_NOT_UNIQUE_MSG), HttpStatus.BAD_REQUEST);
    

    public class ErrorResponse {
        private HttpStatus status;
        private int code;
        private String message;
    
        public ErrorResponse(HttpStatus status, String message) {
            this.message = message;
            this.status = status;
            this.code = status.value();
        }
    }