ErrorHandler用于在一个地方解决多个异常?

时间:2014-03-07 12:02:05

标签: java exception design-patterns

我有ServiceExecutor并运行一个长例程(webervices调用,数据库更新,用户更新等)。由于这些例程可能导致多个错误,我想在一个地方捕获大量错误。因此我用trycatch包装它。但是每个异常应该得到一个自定义错误处理,因此将有5到10行代码来解决错误。

问题:我的runLongRoutine()太大了,所以我不得不考虑错误处理因素。但我不想重新抛出这些例外,因为任何使用runLongRoutine()的班级都不应该关心错误,甚至不能知道错误可能会发生。

我怎样才能在这里调整错误处理?我可以选择一种设计模式吗?

class ServiceExecutor {
    void runLongRoutine() {
        try {
            several(param1);
            calls();
            to(param2);
            different(param3, param1);
            methods();
        } catch (CustomException e) {
            //5-10 lines of code
        } catch (IOException e) {
            //5-10 lines of code
        } catch (NetworkException e) {
            //5-10 lines of code
        }
        //to be continued
    }
}

3 个答案:

答案 0 :(得分:1)

Chain-of-responsibility 模式可能会让您感兴趣。另一种易于实现的方法是捕获任何异常,并向我们发送Map<Class<? extends Throwable>, Handler>,它将异常类型映射到异常处理程序。如果您找不到任何使用默认处理程序或只是重新抛出它。

try {
    // some code
} catch (Throwable e) {
    ExceptionHandler handler = handlers.get(e.getClass());
    if (handler != null) handler.handle(e);
    else DEFAULT_HANDLER.handle(e);
}
// to be continued

答案 1 :(得分:1)

您可以轻松地将异常处理(针对每种类型的异常)和/或实际代码分解为单独的私有方法,例如

class ServiceExecutor {
    void runLongRoutine() {
        try {
            runLongRoutine0();
        } catch (CustomException e) {
            //5-10 lines of code
        } catch (IOException e) {
            //5-10 lines of code
        } catch (NetworkException e) {
            //5-10 lines of code
        }
        //to be continued
    }

    private void runLongRoutine0() throws CustomException, IOException, NetworkException {
        several(param1);
        calls();
        to(param2);
        different(param3, param1);
        methods();
    }
}

class ServiceExecutor {
    void runLongRoutine() {
        try {
            several(param1);
            calls();
            to(param2);
            different(param3, param1);
            methods();
        } catch (CustomException e) {
            handleCustomException(e);
        } catch (IOException e) {
            handleIOException(e);
        } catch (NetworkException e) {
            handleNetworkException(e);
        }
        //to be continued
    }

    private void handleCustomException(CustomException e) { ... }
    private void handleIOException(IOException e) { ... }
    private void handleNetworkException(NetworkException e) { ... }
}
如果确实有必要,甚至可以采用两种方法的组合。

答案 2 :(得分:0)

您可能想尝试AOP。 您可以编写一个处理此方法异常的方面。

相关问题