HTTP Response Exception Handling in Spring 5 Reactive

后端 未结 2 1860
一生所求
一生所求 2021-02-19 21:11

I\'m developing some reactive microservices using Spring Boot 2 and Spring 5 with WebFlux reactive starter.

I\'m facing the following problem: I want to handle all HTTP

2条回答
  •  Happy的楠姐
    2021-02-19 21:46

    I think what you are looking for is WebFluxResponseStatusExceptionHandler the check this for reference.

    In the WebHandler API, a WebExceptionHandler can be used to to handle exceptions from the chain of WebFilter's and the target WebHandler. When using the WebFlux Config, registering a WebExceptionHandler is as simple as declaring it as a Spring bean, and optionally expressing precedence via @Order on the bean declaration or by implementing Ordered.

    This example may help, have not tried it myself.

    @Component
    @Order(-2)
    class RestWebExceptionHandler implements WebExceptionHandler{
    
        @Override
        public Mono handle(ServerWebExchange exchange, Throwable ex) {
            if (ex instanceof PostNotFoundException) {
                exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
    
                // marks the response as complete and forbids writing to it
                return exchange.getResponse().setComplete();
            }
            return Mono.error(ex);
        }
    }
    
    class PostNotFoundException extends RuntimeException {
        PostNotFoundException(String id) {
            super("Post:" + id + " is not found.");
        }
    }
    

提交回复
热议问题