【问题标题】:How to handle Exception and return proper HTTP code in Spring webflux?如何在 Spring webflux 中处理异常并返回正确的 HTTP 代码?
【发布时间】:2019-06-26 16:49:28
【问题描述】:

我有一个方法,它使用 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" */*
}

【问题讨论】:

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


    【解决方案1】:

    你看过Response 类的文档吗?

    您可以使用文档中的静态方法创建自己的Response,然后在onErrorMap 中发送它,而不是Mono.error

    您必须返回如下内容:

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

    您也可以查看link

    【讨论】:

    • 响应不是预定义的类。它是我自己的对象(现在编辑为 ResponseObject)。你能建议任何其他方式吗?
    • 路由器需要一个 ServerResponse。传递 ServerResponse 或 Response。检查文档。
    猜你喜欢
    • 2018-07-20
    • 2021-11-12
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    相关资源
    最近更新 更多