2014-03-13 45 views
0

我验证了我的函数,如果在验证过程中抛出一个异常,我希望在catch和return中停止该方法,由于某种原因,它会继续并且只能在主尝试中捕获/抓住。为什么scala在Catch中没有完成功能

代码:

def updateProduct(request: UpdateProductRequest): BaseResponse[String] = 
{ 
    try 
    { 
     try 
     { 
      ValidateUpdateProductRequest(request) 
     } 
     catch 
     { 
     case ex: Exception => { 
      val errorResponse:ErrorResponse[String] = ErrorResponse(ErrorCode.InvalidParameters, ex.getMessage, 500) 
      errorResponse // <=- This does not return from function.. In debug i get here 
     } 
     } 
     val deleteProductResult = productRepository.updateProduct(request) //I dont want to get here !! 
     DTOResponse(deleteProductResult) 
    } 
    catch 
    { 
    case ex: Exception => { 
     Logger.error("Failed to update product Id = " +request.product.id, ex); 
     var errorResponse:ErrorResponse[String] = ErrorResponse(ErrorCode.GeneralError, ex.getMessage, 500) 
     errorResponse 
    } 
    } 
} 

我明白阶的函数的最后一行是唯一的地方函数将返回,让我怎么从抓回来吗?
原因是我想使用在BaseResponse [字符串]

由于不同错误代码

+0

愚蠢的问题,但你肯定会抛出一个异常在你的'ValidateUpdateProductRequest'方法吗?这可能是因为你传入的主要'catch'是因为另一个异常,例如在'updateProduct'中发生了... –

+0

是的,我一步一步地调试它,我越来越接近第二次尝试..但函数不返回,它继续val val deleteProductResult = productRepository.updateProduct(..),然后得到空引用,因为产品为空 - 这就是验证的一部分.. – ilansch

回答

1

只要您有一个内部表达式要传播到最外层作为结果,您可以将其分配给外部表达式中的临时变量,也可以使用return。因此,举例来说:

def foo: Int = { 
    try { bar } 
    catch { case ikte: IKnowTheAnswerException => return 42 } 
    lotsOfMath 
} 

def foo: Int = { 
    val iKnowIt = { 
    try { bar } 
    catch { case ikte: IKnowTheAnswerException => Some(42) } 
    } 
    iKnowIt.getOrElse(lotsOfMath) 
} 

即使第二模式似乎白白罗嗦,记住,跳出方法与return并不总是显而易见的,尤其是在较长的方法。因此,第二种方法在某些情况下可以更清晰地阅读(特别是当您知道预期模式时)。

+0

我明白返回功能的中间不是“最佳实践”,甚至违背了scala的原则..所以我认为我应该尽量避免它 – ilansch

+0

@ilansch - 你应该编写能够尽可能干净清晰地解决问题的代码。这可能意味着使用'return'!只要知道有一个替代模式(我的第二个例子),可以有优势。 –

+0

也许你可以协助:http://stackoverflow.com/questions/22381645/how-to-break-rest-controller-that-return-action-in-scala-play-framework非常感谢。 – ilansch

相关问题