如何在Mono <responseentity>中正确返回HttpStatus?

时间:2018-06-28 06:27:58

标签: spring-boot reactive-programming spring-webflux project-reactor

我有一个api,它返回一些HttpStatus代码。然后,根据代码,网守将执行一些操作。以下只是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)));
}

现在的问题是,如果我以这种方式返回响应代码,则spring无法从Mono<ResponseEntity>识别状态代码。任何机构都能以某种方式帮助我如何返回statuscode,以便Spring可以识别响应的状态代码

1 个答案:

答案 0 :(得分:0)

您可以创建自己的对象,并在构造中也添加HTTP_STATUS 例如:

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();
}

}