WebExceptionHandler : How to write a body with Spring Webflux

后端 未结 4 1422
情书的邮戳
情书的邮戳 2021-02-19 21:23

I want to handle the Exception of my api by adding a WebExceptionHandler. I can change the status code, but I am stuck when i want to change the body of the response : ex adding

4条回答
  •  长情又很酷
    2021-02-19 22:04

    for anyone looking at a way to write JSON response body, here's a Kotlin code sample:

    fun writeBodyJson(body: Any, exchange: ServerWebExchange) =
        exchange.response.writeWith(
            Jackson2JsonEncoder().encode(
                Mono.just(body),
                exchange.response.bufferFactory(),
                ResolvableType.forInstance(body),
                MediaType.APPLICATION_JSON_UTF8,
                Hints.from(Hints.LOG_PREFIX_HINT, exchange.logPrefix))
        )
    

    not 100% sure that's the way to go though, would like to get some opinions.

提交回复
热议问题