|
|
@@ -9,8 +9,7 @@ import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
|
|
|
import org.springframework.cloud.gateway.support.NotFoundException;
|
|
|
import org.springframework.context.annotation.Configuration;
|
|
|
import org.springframework.core.annotation.Order;
|
|
|
-import org.springframework.core.io.buffer.DataBuffer;
|
|
|
-import org.springframework.http.HttpStatus;
|
|
|
+import org.springframework.core.io.buffer.DataBufferFactory;
|
|
|
import org.springframework.http.MediaType;
|
|
|
import org.springframework.http.server.reactive.ServerHttpResponse;
|
|
|
import org.springframework.lang.NonNull;
|
|
|
@@ -43,7 +42,7 @@ public class GatewayExceptionHandler implements ErrorWebExceptionHandler {
|
|
|
public Mono<Void> handle(ServerWebExchange exchange, @NonNull Throwable ex) {
|
|
|
ServerHttpResponse response = exchange.getResponse();
|
|
|
|
|
|
- if (exchange.getResponse().isCommitted()) {
|
|
|
+ if (response.isCommitted()) {
|
|
|
return Mono.error(ex);
|
|
|
}
|
|
|
|
|
|
@@ -61,17 +60,17 @@ public class GatewayExceptionHandler implements ErrorWebExceptionHandler {
|
|
|
log.error("[网关异常处理]请求方法:{},请求路径: {},异常信息: {}", exchange.getRequest().getMethod(), exchange.getRequest().getPath(), ex.getMessage());
|
|
|
|
|
|
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
|
|
|
- response.setStatusCode(HttpStatus.OK);
|
|
|
+ if (ex instanceof ResponseStatusException) {
|
|
|
+ response.setStatusCode(((ResponseStatusException) ex).getStatus());
|
|
|
+ }
|
|
|
|
|
|
- return response.writeWith(Mono.create(monoSink -> {
|
|
|
+ return response.writeWith(Mono.fromSupplier(() -> {
|
|
|
+ DataBufferFactory bufferFactory = response.bufferFactory();
|
|
|
try {
|
|
|
- byte[] bytes = objectMapper.writeValueAsBytes(Response.buildFailure("B0001", msg));
|
|
|
- DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
|
|
|
-
|
|
|
- monoSink.success(dataBuffer);
|
|
|
- } catch (JsonProcessingException jsonProcessingException) {
|
|
|
- log.error("对象输出异常", jsonProcessingException);
|
|
|
- monoSink.error(jsonProcessingException);
|
|
|
+ return bufferFactory.wrap(objectMapper.writeValueAsBytes(Response.buildFailure("B0001", msg)));
|
|
|
+ } catch (JsonProcessingException e) {
|
|
|
+ log.error("Error writing response", ex);
|
|
|
+ return bufferFactory.wrap(new byte[0]);
|
|
|
}
|
|
|
}));
|
|
|
}
|