|
| 1 | + |
| 2 | +package com.baeldung.reactive.errorhandling; |
| 3 | + |
| 4 | +import java.util.Map; |
| 5 | +import org.springframework.boot.autoconfigure.web.ResourceProperties; |
| 6 | +import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler; |
| 7 | +import org.springframework.boot.web.reactive.error.ErrorAttributes; |
| 8 | +import org.springframework.context.ApplicationContext; |
| 9 | +import org.springframework.core.annotation.Order; |
| 10 | +import org.springframework.http.HttpStatus; |
| 11 | +import org.springframework.http.MediaType; |
| 12 | +import org.springframework.http.codec.ServerCodecConfigurer; |
| 13 | +import org.springframework.stereotype.Component; |
| 14 | +import org.springframework.web.reactive.function.BodyInserters; |
| 15 | +import org.springframework.web.reactive.function.server.RequestPredicates; |
| 16 | +import org.springframework.web.reactive.function.server.RouterFunction; |
| 17 | +import org.springframework.web.reactive.function.server.RouterFunctions; |
| 18 | +import org.springframework.web.reactive.function.server.ServerRequest; |
| 19 | +import org.springframework.web.reactive.function.server.ServerResponse; |
| 20 | +import reactor.core.publisher.Mono; |
| 21 | + |
| 22 | +@Component |
| 23 | +@Order(-2) |
| 24 | +public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler { |
| 25 | + |
| 26 | + public GlobalErrorWebExceptionHandler(GlobalErrorAttributes g, ApplicationContext applicationContext, |
| 27 | + ServerCodecConfigurer serverCodecConfigurer) { |
| 28 | + super(g, new ResourceProperties(), applicationContext); |
| 29 | + super.setMessageWriters(serverCodecConfigurer.getWriters()); |
| 30 | + super.setMessageReaders(serverCodecConfigurer.getReaders()); |
| 31 | + } |
| 32 | + |
| 33 | + @Override |
| 34 | + protected RouterFunction<ServerResponse> getRoutingFunction(final ErrorAttributes errorAttributes) { |
| 35 | + return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse); |
| 36 | + } |
| 37 | + |
| 38 | + private Mono<ServerResponse> renderErrorResponse(final ServerRequest request) { |
| 39 | + |
| 40 | + final Map<String, Object> errorPropertiesMap = getErrorAttributes(request, false); |
| 41 | + |
| 42 | + return ServerResponse.status(HttpStatus.BAD_REQUEST) |
| 43 | + .contentType(MediaType.APPLICATION_JSON_UTF8) |
| 44 | + .body(BodyInserters.fromObject(errorPropertiesMap)); |
| 45 | + } |
| 46 | + |
| 47 | +} |
0 commit comments