广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring Cloud Gateway自定义异常处理Exception Handler的方法小结
  • 198
分享到

Spring Cloud Gateway自定义异常处理Exception Handler的方法小结

2024-04-02 19:04:59 198人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

版本: spring cloud 2020.0.3 常见的方法有 实现自己的 DefaultErrorWEBExceptionHandler 或 仅实现ErrorAttributes

版本: spring cloud 2020.0.3

常见的方法有 实现自己的 DefaultErrorWEBExceptionHandler 或 仅实现ErrorAttributes.

方法1: ErrorWebExceptionHandler (仅供示意)

自定义一个 GlobalErrorAttributes:


@Component
public class GlobalErrorAttributes extends DefaultErrorAttributes{

    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
        Throwable error = super.getError(request);

        Map<String, Object> map = super.getErrorAttributes(request, options);
        map.put("status", httpstatus.BAD_REQUEST.value());
        map.put("message", error.getMessage());
        return map;
    }
}

实现一个


@Component
@Order(-2)
public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {

    public GlobalErrorWebExceptionHandler(GlobalErrorAttributes gea, ApplicationContext applicationContext,
                                          ServerCodecConfigurer serverCodecConfigurer) {
        super(gea, new WebProperties.Resources(), applicationContext);
        super.setMessageWriters(serverCodecConfigurer.getWriters());
        super.setMessageReaders(serverCodecConfigurer.getReaders());
    }

    //渲染htmlJSON
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(final ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    private Mono<ServerResponse> renderErrorResponse(final ServerRequest request) {

        final Map<String, Object> errorPropertiesMap = getErrorAttributes(request, ErrorAttributeOptions.defaults());

        return ServerResponse.status(HttpStatus.BAD_REQUEST)
                .contentType(MediaType.APPLICATION_jsON)
                .body(BodyInserters.fromValue(errorPropertiesMap));
    }
}

方法2, 仅实现一个 ErrorAttributes, 以覆盖默认的 DefaultErrorAttributes


//spring 默认的就很好了.
@Component
public class GatewayErrorAttributes extends DefaultErrorAttributes {

    private static final Logger logger = LoggerFactory.getLogger(GatewayErrorAttributes.class);

    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request,  ErrorAttributeOptions options) {
        Throwable error = super.getError(request);
        Map<String, Object> errorAttributes = new HashMap<>(8);
        errorAttributes.put("message", error.getMessage());
        errorAttributes.put("method", request.methodName());
        errorAttributes.put("path", request.path());

        MergedAnnotation<ResponseStatus> responseStatusAnnotation = MergedAnnotations
                .from(error.getClass(), MergedAnnotations.SearchStrategy.TYPE_HIERARCHY).get(ResponseStatus.class);

        HttpStatus errorStatus = determineHttpStatus(error, responseStatusAnnotation);

        //必须设置, 否则会报错, 因为 DefaultErrorWebExceptionHandler 的 renderErrorResponse 方法会获取此属性, 重新实现 DefaultErrorWebExceptionHandler也可.
        errorAttributes.put("status", errorStatus.value());
        errorAttributes.put("code", errorStatus.value());

        //html view用
        errorAttributes.put("timestamp", new Date());
        //html view 用
        errorAttributes.put("requestId", request.exchange().getRequest().getId());

        errorAttributes.put("error", errorStatus.getReasonPhrase());
        errorAttributes.put("exception", error.getClass().getName());

        return errorAttributes;
    }

    //从DefaultErrorWebExceptionHandler中复制过来的
    private HttpStatus determineHttpStatus(Throwable error, MergedAnnotation<ResponseStatus> responseStatusAnnotation) {
        if (error instanceof ResponseStatusException) {
            return ((ResponseStatusException) error).getStatus();
        }
        return responseStatusAnnotation.getValue("code", HttpStatus.class).orElse(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    
}

这样就可以了.

注意注意: 必须设置 errorAttributes.put("status", errorStatus.value()) , 否则会报错, 因为 DefaultErrorWebExceptionHandler 的 renderErrorResponse 方法会获取此属性. 除非你自己像方法一一样重新实现 DefaultErrorWebExceptionHandler.

然后在网关中访问一个不存在的服务, 即可看到效果.

curl 'http://127.0.0.1:8900/fundmain22/abc/Gogogo?id=1000' --header 'Accept: application/json'
{"exception":"org.springframework.web.server.ResponseStatusException","path":"/fundmain22/abc/gogogo","code":404,"method":"GET","requestId":"094e53e5-1","message":"404 NOT_FOUND","error":"Not Found","status":404,"timestamp":"2021-08-09T11:07:44.106+0000"}

感谢网络上的各种文章...

到此这篇关于Spring Cloud Gateway自定义异常处理Exception Handler的文章就介绍到这了,更多相关Spring Cloud Gateway自定义异常处理内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Spring Cloud Gateway自定义异常处理Exception Handler的方法小结

本文链接: https://www.lsjlt.com/news/132171.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作