import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yxw.common.enums.CommonErrorEnum;
import com.yxw.common.exception.BaseException;
import com.yxw.common.result.BaseResult;
import com.yxw.common.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;
import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;
/**
* @desc: 全局异常处理
* @program: yxw1.0
* @author: qlinc com.yxw.user.handler.GlobalExceptionHandler
* @date: 2022-10-16 13:58:26
*/
@Slf4j
@Order(-1)
@Component
public class GlobalExceptionHandler implements WebExceptionHandler {
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
BaseResult baseResult = determineStatus(ex);
String message = JSONObject.toJSONString(baseResult, SerializerFeature.WriteNullStringAsEmpty);
DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(message.getBytes(StandardCharsets.UTF_8));
exchange.getResponse().setStatusCode(HttpStatus.OK);
//指定编码
// exchange.getResponse().getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
exchange.getResponse().getHeaders().add("Content-Type", "application/json;charset=UTF-8");
return exchange.getResponse().writeWith(Mono.just(buffer));
}
@Nullable
protected BaseResult determineStatus(Throwable ex) {
if (ex instanceof BaseException) {
BaseException e = (BaseException) ex;
BaseResult resultIn = new BaseResult<>();
resultIn.setErrorCode(e.getCode());
resultIn.setErrorMsg(e.getDescription());
resultIn.setPrimaryErrorCode(e.getPrimaryErrorCode());
resultIn.setPrimaryErrorMsg(e.getPrimaryErrorMsg());
resultIn.setPrimaryErrorIP(IpUtil.getIp());
log.error("出现指定错误:{}", ex);
return resultIn;
} else {
BaseResult resultIn = new BaseResult<>();
resultIn.setErrorCode(CommonErrorEnum.UNKNOWN_ERROR.getCode());
resultIn.setErrorMsg(CommonErrorEnum.UNKNOWN_ERROR.getDescription());
// resultIn.setPrimaryErrorCode(e.getPrimaryErrorCode());
resultIn.setPrimaryErrorMsg(ex.getMessage());
resultIn.setPrimaryErrorIP(IpUtil.getIp());
log.error("出现指定系统错误:{}", ex);
return resultIn;
}
}
}
spring cloud gateway全局异常处理
最新推荐文章于 2023-12-11 12:36:59 发布