为什么scala没有在Catch中完成功能

时间:2014-03-13 13:53:14

标签: scala try-catch playframework-2.1

我验证我的函数,如果在验证期间抛出异常,我希望在catch中返回该方法并返回,由于某种原因,它将继续并且仅在主try / 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
     }
  }
}

我理解scala中函数的最后一行是函数返回的唯一位置,所以我如何从catch中返回?
原因是我想在BaseResponse中使用不同的 ErrorCode [string]

谢谢!

1 个答案:

答案 0 :(得分: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跳出方法并不总是显而易见的,尤其是在较长的方法中。因此,在某些情况下,第二个可以更清晰地阅读(特别是当您知道期望模式时)。