【问题标题】:How to properly return HttpStatus in Mono<ResponseEntity>?如何在 Mono<ResponseEntity> 中正确返回 HttpStatus?
【发布时间】:2018-12-07 03:10:12
【问题描述】:

我有一个返回一些HttpStatus 代码的api。并且根据代码,看门人将执行一些操作。以下只是 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&lt;ResponseEntity&gt; 的状态码。任何人都可以帮助我如何以某种方式返回statuscode,以便spring可以识别响应的状态代码

【问题讨论】:

  • ResponseEntity 有一个构建器函数,您可以传递一个“int”,它会为您完成所有工作...... ResponseEntity.status(code).build() 这就是您要寻找的?

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


【解决方案1】:

您可以创建自己的对象,并在构造中添加 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();
    }
}

【讨论】:

    猜你喜欢
    • 2020-03-22
    • 2019-11-22
    • 2021-11-03
    • 1970-01-01
    • 2020-01-06
    • 2020-08-12
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多