代码之家  ›  专栏  ›  技术社区  ›  Ashish

如何在Spring webflux中处理异常并返回正确的HTTP代码?

  •  1
  • Ashish  · 技术社区  · 6 年前

    我有一个方法,它使用Mono.fromfuture(result)给出响应,并抛出状态为400的CustomException。 现在在我的服务类中,当我调用那个方法时,我抛出的错误和代码不会传播到我的客户机(邮递员)。只有信息是我看到的。

    我得到以下格式:-

    {
        "timestamp": "2019-02-01T11:13:32.748+0000",
        "path": "/some_url",
        "status": 500,
        "error": "Internal Server Error",
        "message": "Unable to fetch Response"
    }
    

    期望(我想要实现的目标):-

    {
        "timestamp": "2019-02-01T11:13:32.748+0000",
        "path": "/some_url",
        "status": 400,                           // (my own status)
        "error": "INVALID_ARGUMENT",             // (my own error)
        "message": "Unable to fetch Response"
    }
    

    我的代码:-

    public Mono<ResponseObject> fetchResponse(arg) {
    
       return Mono.just(somedata which will give exception)
          .flatMap(k -> callExternalService(k))
          .onErrorMap(e -> Mono.error(
                new BusinessException("Unable to fetch Response", e))
    
           */* e here is giving :-
            "code" : 400,
            "message" : "Request contains an invalid argument.",
            "status" : "INVALID_ARGUMENT" */*
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   uneq95    6 年前

    你看过 Response 上课?

    您可以创建 回应 使用文档中的静态方法,并发送它,而不是 Mono.error ,在 onErrorMap .

    您必须返回如下内容:

    ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(klass, Klass.class);
    
    ServerResponse.status(status).build();//read doc and set for yourself
    

    你也可以检查这个 link .