我有一个用例,我想处理项目列表。该处理不是原子的,对于列表中的某些项目可能会成功,而对于其他一些项目可能会失败。我想告知 API 用户,对于列表中的某些项目,处理失败。我有3个选择:
返回包含成功项目的列表
返回包含失败项目的列表
抛出异常,表示某些项目失败
如果我采用第三种方法,但仍然想让客户端知道处理失败的项目,我可以将列表添加到异常类中,并让客户端在收到异常时读取此列表吗?这是可取的吗?这里还有什么可以做的吗?
异常类如下所示:
@Getter @Setter
public class SomeProcessingException extends Exception {
private static final long serialVersionUID = 1L;
private List<SomeItem> failedItems;
public SomeProcessingException(String message) {
super(message);
}
}
最佳答案
是的,您可以扩展Exception
并添加失败项目的List
,就像您已经做的那样。
对于部分:
still want to let the clients know the items for which the processing failed
什么是您的客户?最终用户?或者使用您的库的程序员?管理员?
如果是程序员,他可以捕获您的 SomeProcessingException
并从中获取失败项目的列表。
如果是查看日志的最终用户(例如管理员),则必须重写 SomeProcessingException
的 toString
方法。
如果是使用客户端(浏览器、Android 手机、桌面应用程序...)的最终用户,您必须拦截 SomeProcessingException
并显示弹出窗口或类似内容,从中提取失败的项目。
许多标准异常提供对其内部属性的访问,这些属性可由类的使用者使用,例如 URISyntaxException
有方法getIndex()
至:
Returns an index into the input string of the position at which the parse error occurred, or -1 if this position is not known.
同样SQLException
有方法getErrorCode
至:
Retrieves the vendor-specific exception code for this SQLException object.
关于java - 将数据添加到异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54312846/