簡體   English   中英

包裝第三方庫時包裝異常

[英]Wrapping an exception when wrapping a third-party library

我在使用 FIDO 設備為網站注冊和登錄的后端代碼制作一個簡單的 API 時遇到了一個小問題。

我基本上包裝了 yubico u2f 庫,使其更易於使用。 我遇到的問題是有異常,我想從我的 API 向后端服務器com.yubico.u2f.exceptions.NoEligableDevicesException異常,但我不希望我的用戶(后端開發人員)不得不這樣做查看或導入 yubico 庫。

因此,我的解決方案是像這樣包裝該異常:

package com.github.dkanellis.fikey.exceptions;

import com.yubico.u2f.data.DeviceRegistration;

public class NoEligableDevicesException extends com.yubico.u2f.exceptions.NoEligableDevicesException {
    public NoEligableDevicesException(Iterable<? extends DeviceRegistration> devices, String message, Throwable cause) {
        super(devices, message, cause);
    }

    public NoEligableDevicesException(Iterable<? extends DeviceRegistration> devices, String message) {
        super(devices, message);
    }
}

然后throw用戶我的異常包裹yubico例外。 問題是這增加了我的代碼的復雜性,每次發生com.yubico.u2f.exceptions.NoEligableDevicesException異常時,我都必須捕獲它並拋出com.github.dkanellis.fikey.exceptions.NoEligableDevicesException

有一個更好的方法嗎?

問題是這增加了我的代碼的復雜性,每次發生 com.yubico.u2f.exceptions.NoEligableDevicesException 異常時,我都必須捕獲它並拋出 com.github.dkanellis.fikey.exceptions.NoEligableDevicesException。

這不是問題。 這實際上是在應用程序的不同層之間傳播Exception的推薦方法。 我曾經碰到過這樣優秀的文章上傳播的Exception最近。 (這是一篇 .Net 文章,但仍然適用於 Java)

將實際的Exception包裝到您自己的Exception子類中,您可以靈活地更改 API 的底層依賴項,而不會破壞客戶端代碼。 客戶端代碼繼續依賴於您的Exception子類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM