如何处理异常和春季webflux返回正确的HTTP代码?

问题描述 投票:1回答:1

我有使用Mono.fromfuture(结果),并且抛出CustomException 400作为状态其给出响应的方法。现在在我的服务类,当我调用该方法,错误和代码我扔有没有得到传播到我的客户(邮递员)。只有消息是我所看到的。

我得到这个格式如下: -

{
    "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个回答
0
投票

你看在Response类的文档?

你可以创建自己的Response,使用在doc静态方法,并发送,而不是Mono.error,在onErrorMap

你必须返回类似如下:

ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(klass, Klass.class);

ServerResponse.status(status).build();//read doc and set for yourself

您还可以检查此link

© www.soinside.com 2019 - 2024. All rights reserved.