Merge pull request '限制仅当异常响应时才对错误信息进行标准化处理' (#832) from otto/microservices:third-party-tool-forward into third-party-tool-forward
This commit is contained in:
commit
103beae4d8
|
@ -12,7 +12,6 @@ import org.springframework.core.io.buffer.DataBuffer;
|
|||
import org.springframework.core.io.buffer.DataBufferFactory;
|
||||
import org.springframework.core.io.buffer.DataBufferUtils;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.server.reactive.ServerHttpRequest;
|
||||
import org.springframework.http.server.reactive.ServerHttpResponse;
|
||||
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
|
||||
|
@ -40,21 +39,13 @@ public class GlobalResponseFilter implements GlobalFilter, Ordered {
|
|||
ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
|
||||
@Override
|
||||
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
|
||||
MediaType contentType = getHeaders().getContentType();
|
||||
HttpStatus status = getStatusCode() != null ? getStatusCode() : HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
|
||||
// 排除无内容响应和二进制类型
|
||||
if (status == HttpStatus.NO_CONTENT ||
|
||||
(contentType != null && (contentType.includes(MediaType.APPLICATION_OCTET_STREAM) ||
|
||||
contentType.includes(MediaType.MULTIPART_FORM_DATA)))) {
|
||||
if (!status.isError()) {
|
||||
return super.writeWith(body);
|
||||
}
|
||||
|
||||
// 保留原始状态码
|
||||
originalResponse.setStatusCode(HttpStatus.OK);
|
||||
getHeaders().setContentType(MediaType.APPLICATION_JSON);
|
||||
|
||||
return Flux.from(body).<String>handle((dataBuffer, synchronousSink) -> {
|
||||
if (status.isError()) {
|
||||
byte[] bytes = new byte[dataBuffer.readableByteCount()];
|
||||
dataBuffer.read(bytes);
|
||||
//释放掉内存
|
||||
|
@ -62,13 +53,15 @@ public class GlobalResponseFilter implements GlobalFilter, Ordered {
|
|||
String result = new String(bytes, StandardCharsets.UTF_8);
|
||||
if (!JSON.isValid(result)) {
|
||||
synchronousSink.next(result);
|
||||
} else {
|
||||
synchronousSink.complete();
|
||||
return;
|
||||
}
|
||||
}
|
||||
synchronousSink.complete();
|
||||
|
||||
}).flatMap(resBody -> {
|
||||
// 保留原始状态码
|
||||
originalResponse.setStatusCode(HttpStatus.OK);
|
||||
byte[] bytes = JSON.toJSONBytes(AjaxResult.error(resBody));
|
||||
|
||||
getHeaders().setContentLength(bytes.length);
|
||||
DataBuffer buffer = bufferFactory.wrap(bytes);
|
||||
return super.writeWith(Mono.just(buffer));
|
||||
|
|
Loading…
Reference in New Issue