78 lines
2.5 KiB
Java
78 lines
2.5 KiB
Java
package com.bonus.gateway.handler;
|
|
|
|
import com.bonus.common.core.exception.GlobalException;
|
|
import com.bonus.common.core.exception.ServiceException;
|
|
import com.bonus.common.core.utils.StringUtils;
|
|
import com.bonus.common.core.web.domain.AjaxResult;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.cloud.gateway.support.NotFoundException;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
|
|
import org.springframework.context.annotation.Configuration;
|
|
import org.springframework.core.annotation.Order;
|
|
import org.springframework.http.server.reactive.ServerHttpResponse;
|
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
import org.springframework.web.server.ResponseStatusException;
|
|
import org.springframework.web.server.ServerWebExchange;
|
|
import com.bonus.common.core.utils.ServletUtils;
|
|
import reactor.core.publisher.Mono;
|
|
|
|
import javax.servlet.http.HttpServletRequest;
|
|
|
|
/**
|
|
* 网关统一异常处理
|
|
*
|
|
* @author bonus
|
|
*/
|
|
@Order(-1)
|
|
@Configuration
|
|
public class GatewayExceptionHandler implements ErrorWebExceptionHandler
|
|
{
|
|
@Value("${system.jie-enable}")
|
|
public boolean jaData;
|
|
|
|
|
|
private static final Logger log = LoggerFactory.getLogger(GatewayExceptionHandler.class);
|
|
/**
|
|
* 验证码异常处理
|
|
*/
|
|
@ExceptionHandler(GlobalException.class)
|
|
public AjaxResult handleGlobalException(ServiceException e, HttpServletRequest request)
|
|
{
|
|
log.error(e.getMessage(), e);
|
|
Integer code = e.getCode();
|
|
return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());
|
|
}
|
|
|
|
@Override
|
|
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex)
|
|
{
|
|
ServerHttpResponse response = exchange.getResponse();
|
|
|
|
if (exchange.getResponse().isCommitted())
|
|
{
|
|
return Mono.error(ex);
|
|
}
|
|
|
|
String msg;
|
|
|
|
if (ex instanceof NotFoundException)
|
|
{
|
|
msg = "服务未找到";
|
|
}
|
|
else if (ex instanceof ResponseStatusException)
|
|
{
|
|
ResponseStatusException responseStatusException = (ResponseStatusException) ex;
|
|
msg = responseStatusException.getMessage();
|
|
}
|
|
else
|
|
{
|
|
msg = "内部服务器错误";
|
|
}
|
|
|
|
log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage());
|
|
|
|
return ServletUtils.webFluxResponseWriter(response, msg,jaData);
|
|
}
|
|
} |