dubbo filter 擴(kuò)展 以及 重寫(xiě) dubbo ExceptionFilter

dubbo 自身提供了filter 的擴(kuò)展,用于入?yún)⒑又剩鰠⒓讲眩?guī)范返回參數(shù) 都是非常實(shí)用的,本文就以重寫(xiě)dubbo 自身的ExceptionFilter 為例 詳細(xì)說(shuō)明 dubbo 的filter功能

我們的項(xiàng)目中很多情況下都會(huì)拋出一些自定義異常來(lái)替代返回錯(cuò)誤碼掀鹅,但是在dubbo服務(wù)中往往不能達(dá)到理想的效果散休,因?yàn)閐ubbo 的ExceptionFilter過(guò)濾器會(huì)將我們的異常信息進(jìn)行包裝,我們重寫(xiě)一下ExceptioFilter 就可以輕松的實(shí)現(xiàn)我們的效果

  1. 將ExceptionFilter copy 到我們的項(xiàng)目改名為DubboExceptionFilter或者新建一個(gè)Filter 繼承com.alibaba.dubbo.rpc.Filter
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.utils.ReflectUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.RpcResult;
import com.alibaba.dubbo.rpc.service.GenericService;

import java.lang.reflect.Method;

@Activate(group = Constants.PROVIDER)
public class DubboExceptionFilter implements Filter {

    private final Logger logger;

    public DubboExceptionFilter() {
        this(LoggerFactory.getLogger(DubboExceptionFilter.class));
    }

    public DubboExceptionFilter(Logger logger) {
        this.logger = logger;
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            Result result = invoker.invoke(invocation);
            if (result.hasException() && GenericService.class != invoker.getInterface()) {
                try {
                    Throwable exception = result.getException();

                    // directly throw if it's checked exception
                    if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) {
                        return result;
                    }
                    // directly throw if the exception appears in the signature
                    try {
                        Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes());
                        Class<?>[] exceptionClassses = method.getExceptionTypes();
                        for (Class<?> exceptionClass : exceptionClassses) {
                            if (exception.getClass().equals(exceptionClass)) {
                                return result;
                            }
                        }
                    } catch (NoSuchMethodException e) {
                        return result;
                    }

                    // for the exception not found in method's signature, print ERROR message in server's log.
                    logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost()
                            + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName()
                            + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception);

                    // directly throw if exception class and interface class are in the same jar file.
                    String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface());
                    String exceptionFile = ReflectUtils.getCodeBase(exception.getClass());
                    if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)) {
                        return result;
                    }
                    // directly throw if it's JDK exception
                    String className = exception.getClass().getName();
                    if (className.startsWith("java.") || className.startsWith("javax.")) {
                        return result;
                    }
                    if (className.startsWith("com.dliberty")) {
                        return result;
                    }
                    // directly throw if it's dubbo exception
                    if (exception instanceof RpcException) {
                        return result;
                    }

                    // otherwise, wrap with RuntimeException and throw back to the client
                    return new RpcResult(new RuntimeException(StringUtils.toString(exception)));
                } catch (Throwable e) {
                    logger.warn("Fail to ExceptionFilter when called by " + RpcContext.getContext().getRemoteHost()
                            + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName()
                            + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e);
                    return result;
                }
            }
            return result;
        } catch (RuntimeException e) {
            logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost()
                    + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName()
                    + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e);
            throw e;
        }
    }
}

image.png
  1. 在此處加上一段代碼來(lái)過(guò)濾我們項(xiàng)目中的異常以免被dubbo 重新封裝為 RpcException

  2. 在resources目錄下添加純文本文件META-INF/dubbo/com.alibaba.dubbo.rpc.Filter并添加內(nèi)容

    dubboExceptionFilter=com.dliberty.core.exception.DubboExceptionFilter
    
image.png
  1. 修改dubbo 的配置文件乐尊,將DubboExceptionFilter加載進(jìn)去并且去掉自身的ExceptionFilter

    <dubbo:provider filter="dubboExceptionFilter,-exception" ></dubbo:provider>
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末戚丸,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子扔嵌,更是在濱河造成了極大的恐慌限府,老刑警劉巖夺颤,帶你破解...
    沈念sama閱讀 218,204評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異胁勺,居然都是意外死亡世澜,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門姻几,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)宜狐,“玉大人,你說(shuō)我怎么就攤上這事蛇捌「Ш悖” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,548評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵络拌,是天一觀的道長(zhǎng)俭驮。 經(jīng)常有香客問(wèn)我,道長(zhǎng)春贸,這世上最難降的妖魔是什么混萝? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,657評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮萍恕,結(jié)果婚禮上逸嘀,老公的妹妹穿的比我還像新娘。我一直安慰自己允粤,他們只是感情好崭倘,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著类垫,像睡著了一般司光。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上悉患,一...
    開(kāi)封第一講書(shū)人閱讀 51,554評(píng)論 1 305
  • 那天残家,我揣著相機(jī)與錄音,去河邊找鬼售躁。 笑死坞淮,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的陪捷。 我是一名探鬼主播回窘,決...
    沈念sama閱讀 40,302評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼揩局!你這毒婦竟也來(lái)了毫玖?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,216評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎付枫,沒(méi)想到半個(gè)月后烹玉,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,661評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡阐滩,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評(píng)論 3 336
  • 正文 我和宋清朗相戀三年二打,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片掂榔。...
    茶點(diǎn)故事閱讀 39,977評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡继效,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出装获,到底是詐尸還是另有隱情瑞信,我是刑警寧澤,帶...
    沈念sama閱讀 35,697評(píng)論 5 347
  • 正文 年R本政府宣布穴豫,位于F島的核電站凡简,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏精肃。R本人自食惡果不足惜秤涩,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望司抱。 院中可真熱鬧筐眷,春花似錦、人聲如沸习柠。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,898評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)津畸。三九已至振定,卻和暖如春必怜,著一層夾襖步出監(jiān)牢的瞬間肉拓,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,019評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工梳庆, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留暖途,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,138評(píng)論 3 370
  • 正文 我出身青樓膏执,卻偏偏與公主長(zhǎng)得像驻售,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子更米,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容