包装第三方库时包装异常

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.

有更好的方法吗?

The problem is that this add complexity to my code and everytime the com.yubico.u2f.exceptions.NoEligableDevicesException exception occurs I have to catch it and throw the com.github.dkanellis.fikey.exceptions.NoEligableDevicesException.

这不是问题。这实际上是在应用程序的不同层之间传播 Exception 的推荐方法。我最近看到了 this 一篇关于传播 Exception 的优秀文章。 (这是一篇 .Net 文章,但仍然适用于 Java)

将实际的 Exception 包装到您自己的 Exception 子类中,使您可以灵活地更改 API 的基础依赖项,而不会破坏客户端代码。客户端代码继续依赖于您的 Exception 子类。