spring cloud gateway统一异常拦截处理

直接贴代码,如下:

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;
import java.util.HashMap;
import java.util.Map;

public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger(JsonExceptionHandler.class);
    public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
        ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    /**
     * 获取异常属性
     */
    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
        int code = HttpStatus.INTERNAL_SERVER_ERROR.value();
        Throwable error = super.getError(request);
        String message;
        // 用于error级别记录日志,方便排查问题
         message = this.buildMessage(request, error);
        if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) {
            code = HttpStatus.NOT_FOUND.value();
            message = "找不到url";
        }
        // 判断是否触发限流异常
        if (error instanceof com.alibaba.csp.sentinel.slots.block.flow.FlowException) {
            code = 409;
            message = "触发限流";
        }
        return response(code, message);
    }

    /**
     * 指定响应处理方法为JSON处理的方法
     *
     * @param errorAttributes
     */
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    /**
     * 根据code获取对应的HttpStatus
     * 
     * @param errorAttributes
     * @return
     */
    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {
        int statusCode = (int)errorAttributes.get("status");
        return statusCode;
    }

    /**
     * 构建异常信息
     *
     * @param request
     * @param ex
     * @return
     */
    private String buildMessage(ServerRequest request, Throwable ex) {
        StringBuilder message = new StringBuilder("Failed to handle request [");
        message.append(request.methodName());
        message.append(" ");
        message.append(request.uri());
        message.append("]");
        if (ex != null) {
            message.append(": ");
            message.append(ex.getMessage());
        }
        // 记录日志,方便排查问题
        logger.error(message.toString(), ex);
        return "网络发生404";
    }

    /**
     * 构建返回的JSON数据格式
     * @param status
     * 状态码
     * @param errorMessage
     * 异常信息
     * @return
     */
    public static Map<String, Object> response(int status, String errorMessage) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", status);
        map.put("status", 200);// 设置抛异常一直status为200
        map.put("message", errorMessage);
        logger.error("异常返回 {}", map);
        String response = JSON.toJSONString(map);
        map.put("response", response);
        return map;
    }

}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud Gateway是一个基于Spring实现的微服务网关,它提供了一种灵活、强大的方式来构建、管理和路由微服务的请求流量。在使用Spring Cloud Gateway时,我们可以通过编写自定义的全局过滤器来实现全局拦截异常的功能。 要实现全局拦截异常,首先我们需要创建一个全局异常处理的类,该类需要继承自AbstractGatewayExceptionHandler。在这个类中,我们可以根据自己的需求重写相应的方法来处理异常。 比如,可以重写handleException方法来处理异常,并返回自定义的错误响应。在这个方法中,我们可以根据不同的异常类型进行不同的处理,比如返回特定的错误码、错误信息等。 然后,我们需要将这个全局异常处理类注册到Spring Cloud Gateway中。在Java配置文件中,添加一个Bean,将全局异常处理类的实例作为参数传入。 通过以上步骤,我们就可以实现Spring Cloud Gateway的全局拦截异常功能了。当微服务中出现异常时,系统会自动调用全局异常处理类中的相应方法来处理异常,并返回自定义的错误响应。 总之,使用Spring Cloud Gateway可以方便地实现全局拦截异常的功能。我们只需要编写一个自定义的全局异常处理类,并将其注册到Spring Cloud Gateway中即可。这样,我们就能够在微服务中统一处理各种异常,并返回自定义的错误信息。这样不仅提高了系统的可维护性,还可以提升用户的体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值