From 92e769465ef600f9ddcb7dd1b3fbb7c57d99e977 Mon Sep 17 00:00:00 2001 From: lishangbu Date: Tue, 26 May 2020 12:21:16 +0800 Subject: [PATCH] =?UTF-8?q?:sparkles:=20Introducing=20new=20features.#I1IA?= =?UTF-8?q?ND=20=E7=BD=91=E5=85=B3=E9=80=9A=E7=94=A8=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E5=A4=84=E7=90=86=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handler/GlobalExceptionHandler.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 pig-gateway/src/main/java/com/pig4cloud/pig/gateway/handler/GlobalExceptionHandler.java diff --git a/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/handler/GlobalExceptionHandler.java b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/handler/GlobalExceptionHandler.java new file mode 100644 index 00000000..f6e26b17 --- /dev/null +++ b/pig-gateway/src/main/java/com/pig4cloud/pig/gateway/handler/GlobalExceptionHandler.java @@ -0,0 +1,58 @@ +package com.pig4cloud.pig.gateway.handler; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.pig4cloud.pig.common.core.util.R; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.core.io.buffer.DataBufferFactory; +import org.springframework.http.MediaType; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.handler.ResponseStatusExceptionHandler; +import reactor.core.publisher.Mono; + +/** + * 网关异常通用处理器,只作用在webflux 环境下 , 优先级低于 {@link ResponseStatusExceptionHandler} 执行 + * + * @author 冷酱 + * @date 2020/5/26 + */ +@Slf4j +@Order(-1) +@Configuration +@RequiredArgsConstructor +public class GlobalExceptionHandler implements ErrorWebExceptionHandler { + private final ObjectMapper objectMapper; + + @Override + public Mono 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 { + return bufferFactory.wrap(objectMapper.writeValueAsBytes(R.failed(ex.getMessage()))); + } catch (JsonProcessingException e) { + log.error("Error writing response", ex); + return bufferFactory.wrap(new byte[0]); + } + })); + } + +}