您好,欢迎访问一九零五行业门户网

Spring Cloud Gateway的全局异常处理的介绍(代码示例)

本篇文章给大家带来的内容是关于spring cloud gateway的全局异常处理的介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
spring cloud gateway中的全局异常处理不能直接用@controlleradvice来处理,通过跟踪异常信息的抛出,找到对应的源码,自定义一些处理逻辑来符合业务的需求。
网关都是给接口做代理转发的,后端对应的都是rest api,返回数据格式都是json。如果不做处理,当发生异常时,gateway默认给出的错误信息是页面,不方便前端进行异常处理。
需要对异常信息进行处理,返回json格式的数据给客户端。下面先看实现的代码,后面再跟大家讲下需要注意的地方。
自定义异常处理逻辑:
package com.cxytiandi.gateway.exception;import java.util.hashmap;import java.util.map;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.reactive.error.errorattributes;import org.springframework.context.applicationcontext;import org.springframework.http.httpstatus;import org.springframework.web.reactive.function.server.requestpredicates;import org.springframework.web.reactive.function.server.routerfunction;import org.springframework.web.reactive.function.server.routerfunctions;import org.springframework.web.reactive.function.server.serverrequest;import org.springframework.web.reactive.function.server.serverresponse;/** * 自定义异常处理 *  * <p>异常时用json代替html异常信息<p> *  * @author yinjihuan * */public class jsonexceptionhandler extends defaulterrorwebexceptionhandler {    public jsonexceptionhandler(errorattributes errorattributes, resourceproperties resourceproperties,            errorproperties errorproperties, applicationcontext applicationcontext) {        super(errorattributes, resourceproperties, errorproperties, applicationcontext);    }    /**     * 获取异常属性     */    @override    protected map<string, object> geterrorattributes(serverrequest request, boolean includestacktrace) {        int code = 500;        throwable error = super.geterror(request);        if (error instanceof org.springframework.cloud.gateway.support.notfoundexception) {            code = 404;        }        return response(code, this.buildmessage(request, error));    }    /**     * 指定响应处理方法为json处理的方法     * @param errorattributes     */    @override    protected routerfunction<serverresponse> getroutingfunction(errorattributes errorattributes) {        return routerfunctions.route(requestpredicates.all(), this::rendererrorresponse);    }    /**     * 根据code获取对应的httpstatus     * @param errorattributes     */    @override    protected httpstatus gethttpstatus(map<string, object> errorattributes) {        int statuscode = (int) errorattributes.get(code);        return httpstatus.valueof(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());        }        return message.tostring();    }    /**     * 构建返回的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(message, errormessage);        map.put(data, null);        return map;    }}
覆盖默认的配置:
package com.cxytiandi.gateway.exception;import java.util.collections;import java.util.list;import org.springframework.beans.factory.objectprovider;import org.springframework.boot.autoconfigure.web.resourceproperties;import org.springframework.boot.autoconfigure.web.serverproperties;import org.springframework.boot.context.properties.enableconfigurationproperties;import org.springframework.boot.web.reactive.error.errorattributes;import org.springframework.boot.web.reactive.error.errorwebexceptionhandler;import org.springframework.context.applicationcontext;import org.springframework.context.annotation.bean;import org.springframework.context.annotation.configuration;import org.springframework.core.ordered;import org.springframework.core.annotation.order;import org.springframework.http.codec.servercodecconfigurer;import org.springframework.web.reactive.result.view.viewresolver;/** * 覆盖默认的异常处理 *  * @author yinjihuan * */@configuration@enableconfigurationproperties({serverproperties.class, resourceproperties.class})public class errorhandlerconfiguration {    private final serverproperties serverproperties;    private final applicationcontext applicationcontext;    private final resourceproperties resourceproperties;    private final list<viewresolver> viewresolvers;    private final servercodecconfigurer servercodecconfigurer;    public errorhandlerconfiguration(serverproperties serverproperties,                                     resourceproperties resourceproperties,                                     objectprovider viewresolversprovider,                                     servercodecconfigurer servercodecconfigurer,                                     applicationcontext applicationcontext) {        this.serverproperties = serverproperties;        this.applicationcontext = applicationcontext;        this.resourceproperties = resourceproperties;        this.viewresolvers = viewresolversprovider.getifavailable(collections::emptylist);        this.servercodecconfigurer = servercodecconfigurer;    }    @bean    @order(ordered.highest_precedence)    public errorwebexceptionhandler errorwebexceptionhandler(errorattributes errorattributes) {        jsonexceptionhandler exceptionhandler = new jsonexceptionhandler(                errorattributes,                 this.resourceproperties,                this.serverproperties.geterror(),                 this.applicationcontext);        exceptionhandler.setviewresolvers(this.viewresolvers);        exceptionhandler.setmessagewriters(this.servercodecconfigurer.getwriters());        exceptionhandler.setmessagereaders(this.servercodecconfigurer.getreaders());        return exceptionhandler;    }    }
注意点异常时如何返回json而不是html?在org.springframework.boot.autoconfigure.web.reactive.error.defaulterrorwebexceptionhandler中的getroutingfunction()方法就是控制返回格式的,原代码如下:
@overrideprotected routerfunction<serverresponse> getroutingfunction(            errorattributes errorattributes) {       return routerfunctions.route(acceptstexthtml(), this::rendererrorview)                .androute(requestpredicates.all(), this::rendererrorresponse);}
这边优先是用html来显示的,想用json的改下就可以了,如下:
protected routerfunction<serverresponse> getroutingfunction(errorattributes errorattributes) {       return routerfunctions.route(requestpredicates.all(), this::rendererrorresponse);}
gethttpstatus需要重写原始的方法是通过status来获取对应的httpstatus的,代码如下:
protected httpstatus gethttpstatus(map<string, object> errorattributes) {      int statuscode = (int) errorattributes.get(status);      return httpstatus.valueof(statuscode);}
如果我们定义的格式中没有status字段的话,这么就会报错,找不到对应的响应码,要么返回数据格式中增加status子段,要么重写,我这边返回的是code,所以要重写,代码如下:
@overrideprotected httpstatus gethttpstatus(map<string, object> errorattributes) {    int statuscode = (int) errorattributes.get(code);    return httpstatus.valueof(statuscode);}
以上就是spring cloud gateway的全局异常处理的介绍(代码示例)的详细内容。
其它类似信息

推荐信息