2013-07-12 120 views
3

我需要显示每个在适当的位置服务获得了一些验证消息,我解决它把消息中的异常:可以在异常中存储其他对象吗?

class InvalidInputException extends RuntimeException { 
    def errors 
    InvalidInputException(String s) { 
     super(s) 
    } 

    InvalidInputException(String s, errors) { 
     super(s) 
     this.errors = errors 
    } 
} 

这样的话,我可能会抛出异常发送错误:

if (errors) { 
    throw new InvalidInputException("There were some errors", errors) 
} 

..然后我在控制器处理错误后,经过捕获异常:

... 
catch (InvalidInputException e) { 
    if (e.errors) { 
     // set them up to display appropriately 
    } 
    // render the view 
} 

现在,我读过Groovy的例外可能花费太多,所以...这太糟糕了吗? 在异常中可能会遇到什么问题?

这比处理返回的错误消息要容易得多,而且代码要短得多。

+4

看起来对我来说......您在哪里阅读过_“Groovy的例外可能花费太多”_?另外,你对“太多”的定义是什么? –

+3

一个例外花费太多的想法对我来说似乎很奇怪。例外是例外。如果你处于抛出异常(它们是昂贵的,也是普通的java)对你的性能有影响的地步,要么你真的做得非常糟糕(抛出太多例外),要么你做得很好,你可能负担得起重新设计以解决问题。 – loteq

+0

@tim_yates我认为OP想要说出loteq对昂贵的说法。例如,这里讨论[这里](http://stackoverflow.com/questions/299068/how-slow-are-java-exceptions)。 –

回答

2

如果你关心Java中的异常性能,我建议你看看这个other question

如果您不创建异常,另一种可能性是让您的服务返回一个表示此流程结果的对象。喜欢的东西:

class MyServiceResult { 
    List<String> errorCodes = [] //codes for i18n 

    void addErrorCode(String errorCode) { 
    errorCodes << errorCode //add error to list 
    } 

    boolean isValid() { 
    return (!(errorCodes.size() > 0)) //if we have errors then isn't valid. 
    } 

    List<String> getErrorCodes() { 
    return errorCodes.asImmutable() 
    } 

} 

而只是用它在你的服务方法

class MyService { 
    MyServiceResult someMethod() { 
    MyServiceResult result = new MyServiceResult() 
    ... 
    result.addErrorCode('some.key.here') 
    ... 
    return result 
    } 
} 

class MyController { 
    def myService 
    def action() { 
    MyServiceResult result = myService.someMethod() 
    if(!result.isValid()) { 
     //handle errors 
    } 
    } 
} 

不过要说的是它可以比创建一个例外 2倍速度较慢这一点很重要。您可以查看this post中的所有详细信息。

+1

如果有任何事务,如果不从服务层抛出'RuntimeException'或'Error',则不会回滚事务。 :) – dmahapatro

+0

好抓!如果你需要更多的控制,你可以让你的服务不是事务性的,而是手动启动。 –

相关问题