Bob*_*r02 3 java error-handling
我对以下设计方法感到困惑:
Map<String, BigDecimal> foo(Parameter p){ ... }
Run Code Online (Sandbox Code Playgroud)
此方法采用复杂的方法Parameter并返回地图名称 - >值.在许多情况下,基于参数的某些基础calue,结果映射将是相同的,此外,只有少数不同的映射可以返回,因此这些将被缓存.但是,在最初创建映射时,可能存在不同类型的错误 - 某些字符串值可能不正确,某些值可能<0,因此应跳过等等.这些错误可能具有不同的性质.我想返回这个地图,但是当执行每个地图的初始化时,也能够标记这些错误,理想情况下只能标记一次.最干净的方法是什么?
这是一个相当不寻常的要求 - 如果您可以在内部错误的情况下生成有效结果,则应该返回该结果; 如果没有,抛出异常.
But if you do want to return this additional information, then I see you have broadly two options available:
foo(), accumulate any internal errors in some field. Expose an additional getFooErrors() method to allow callers to inspect what happened. And possibly a getFooErrorSeverity() method if you need to tell callers the degree to which these errors impacted on the quality of your result map.Immutable/functional. Return the information from above (exceptions and maybe a severity score) as part of your method. Instead of returning a Map<String, BigDecimal>, return an object which contains the map, as well as the exception details. E.g:
public class FooResult {
public final Map<String, BigDecimal> result;
public final List<Throwable> errors;
public final int errorSeverity;
// Constructor elided
}
Run Code Online (Sandbox Code Playgroud)The first approach is similar to how java.io.PrintWriter works in the standard library. It swallows any IOExceptions encountered by its I/O methods, and exposes a checkError() method to allow callers to see if the writer encountered any exceptions.
I prefer the second because it doesn't impact thread-safety, it gives the client all the information up-front, and it's neatly coupled with the scope where the error was encountered.
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |