从控制器中捕获的异常抛出异常 [英] Exception Thrown From Service Not Being Caught in Controller

查看:77
本文介绍了从控制器中捕获的异常抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Grails服务中,我有如下代码:

  def createCharge(chargeParams){
try {
def charge = Charge.create(chargeParams)
} catch(CardException e){
throw e
}
}

在我的控制器中,我执行以下操作:

 尝试{
service.createCharge(chargeParams)
} catch(CardException e){

}

但是,我的控制器没有捕获CardException的重新抛出。如果我通过以下方式将CardException包装在RuntimeException中:

  throw new RuntimeException(e)

和/或从catch中删除签名以仅捕获(e)而不键入它,它可以工作,但我从异常中丢失了一些信息,例如消息。



值得注意的是,CardException是一个异常,而不是一个RuntimeException。我不确定这是否重要。

解决方案

与Java不同,您不必声明(checked)由Groovy方法抛出,因为任何未声明的已检查异常都包装在 UndeclaredThrowableException 中。所以这个:

  def createCharge(chargeParams){
try {
def charge = Charge.create( (CardException e){
throw e
}
}

实际上与以下内容相同:

  def createCharge(chargeParams)throws UndeclaredThrowableException {
尝试{
def charge = Charge.create(chargeParams)
} catch(CardException e){
throw new UndeclaredThrowableException(e)
}
}

上述抛出的异常,显然不会被捕获:

  try {
service.createCharge(chargeParams)
} catch(CardException e){

}

但它会被抓住:

  try {
service.createCharge(chargeParams)
} catch(e){

}

因为这只是一个简写:

  try {
service.createCharge(chargeParams)
} catch(Exception e){

}


In my Grails service I have code like the following:

def createCharge(chargeParams) {
  try {
    def charge = Charge.create(chargeParams)
  } catch (CardException e) {
    throw e
  }
}

From my controller I do the following:

try  {
   service.createCharge(chargeParams)
} catch(CardException e) {

}

However, my controller is not catching the re-throwing of the CardException. If I wrap CardException in a RuntimeException via:

throw new RuntimeException(e)

and/or remove the signature from the catch to just catch(e) without typing it, it works, but I lose some information from the exception, like the message.

As a note, CardException is an Exception, not a RuntimeException. I'm not sure if that matters.

解决方案

Unlike Java, you don't have to declare the (checked) exceptions that are thrown by a Groovy method, because any undeclared checked exceptions are wrapped in an UndeclaredThrowableException. So this:

def createCharge(chargeParams) {
  try {
    def charge = Charge.create(chargeParams)
  } catch (CardException e) {
    throw e
  }
}

is effectively the same as:

def createCharge(chargeParams) throws UndeclaredThrowableException {
  try {
    def charge = Charge.create(chargeParams)
  } catch (CardException e) {
    throw new UndeclaredThrowableException(e)
  }
}

the exception thrown by the above, obviously wouldn't be caught by:

try  {
   service.createCharge(chargeParams)
} catch(CardException e) {

}

But it will be caught by:

try  {
   service.createCharge(chargeParams)
} catch(e) {

}

Because this is just a shorthand for:

try  {
   service.createCharge(chargeParams)
} catch(Exception e) {

}

这篇关于从控制器中捕获的异常抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆