我在为带有 FIDO 设备的网站的注册和登录后端代码制作一个简单的 API 时遇到了一个小问题。
我基本上包装了 yubico u2f 库并使其更易于使用。我遇到的问题是有异常,我想从我的 API 向后端服务器抛出 com.yubico.u2f.exceptions.NoEligableDevicesException
异常(exception),但我不希望我的用户(后端开发人员)必须查看或导入 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.
这不是问题。这实际上是在应用程序的不同层之间传播异常
的推荐方法。我遇到过this最近关于传播异常
的优秀文章。 (这是一篇 .Net 文章,但仍然适用于 Java)
将实际的 Exception
包装到您自己的 Exception
子类中,使您可以灵活地更改 API 的底层依赖项,而无需破坏客户端代码。客户端代码继续依赖于您的 Exception
子类。
关于java - 包装第三方库时包装异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31100081/