Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing Custom Runtime exception in Spring Cloud Gateway Filters

We are using Spring Cloud Gateway with Spring Boot 2 and reactive webflux module. There is an Authentication Filter which is added for one of the route. Now if we throw a RuntimeException with a particular status code, it is really not picking up. Earlier this auth check was part of the HandlerInterceptor in Spring, now we cannot use the web module along with webflux(Conflict from Spring cloud gateway). Ex:

@Override
public GatewayFilter apply(Object config) {
   ServerHttpRequest httpRequest = exchange.getRequest();
   if(!someUtil.validRequest(httpRequest) {
          throw new RuntimeException("Throw 401 Unauthorized with Custom error code and message");
   }
}

Currently the actual response always gives 500 internal server error. from where is this coming from? Can we get hold of the errors from Filters here?

like image 991
Santosh Avatar asked Nov 07 '22 06:11

Santosh


1 Answers

You can implement a custom error handler, here is the spring boot document.

Or you can simply throw a ResponseStatusException, the default error handler will render the specific status.

like image 196
steven.tong Avatar answered Nov 15 '22 12:11

steven.tong