SpringCloud Gateway统一异常处理

young 467 2021-10-18
@Slf4j
@Order(-1)
@Configuration
@RequiredArgsConstructor
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {
    private final ObjectMapper objectMapper;

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        if (response.isCommitted()) {
            return Mono.error(ex);
        }

        // header set
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        if (ex instanceof ResponseStatusException) {
            response.setStatusCode(((ResponseStatusException) ex).getStatus());
        }

        return response
                .writeWith(Mono.fromSupplier(() -> {
                    DataBufferFactory bufferFactory = response.bufferFactory();
                    try {
                        log.warn("Incoming request [{}] occur exception [{}], cannot be handled", exchange.getRequest().getURI(), ex.getMessage());
                        return bufferFactory.wrap(objectMapper.writeValueAsBytes(ApiResponse.failResponse(ex.getMessage())));
                    } catch (JsonProcessingException e) {
                        log.error("Error writing response", ex);
                        return bufferFactory.wrap(new byte[0]);
                    }
                }));
    }

}