mirror of
https://gitee.com/log4j/pig.git
synced 2024-12-23 05:00:23 +08:00
✨ Introducing new features.#I1IAND 网关通用异常处理器
This commit is contained in:
parent
98a382c2b2
commit
92e769465e
@ -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<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 {
|
||||||
|
return bufferFactory.wrap(objectMapper.writeValueAsBytes(R.failed(ex.getMessage())));
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
log.error("Error writing response", ex);
|
||||||
|
return bufferFactory.wrap(new byte[0]);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user