scala为什么不在Catch中完成函数
我验证我的函数,如果在验证过程中抛出异常,我希望停止catch中的方法并返回,出于某种原因,它将继续并仅在try/catch中捕获 代码:scala为什么不在Catch中完成函数,scala,try-catch,playframework-2.1,Scala,Try Catch,Playframework 2.1,我验证我的函数,如果在验证过程中抛出异常,我希望停止catch中的方法并返回,出于某种原因,它将继续并仅在try/catch中捕获 代码: def updateProduct(request: UpdateProductRequest): BaseResponse[String] = { try { try { ValidateUpdateProductRequest(request) } 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
}
}
}
def updateProduct(请求:UpdateProductRequest):BaseResponse[String]=
{
尝试
{
尝试
{
ValidateUpdateProductRequest(请求)
}
抓住
{
案例示例:异常=>{
val errorResponse:errorResponse[String]=errorResponse(ErrorCode.InvalidParameters,ex.getMessage,500)
错误响应//{
Logger.error(“未能更新产品Id=“+request.product.Id,ex”);
var errorResponse:errorResponse[String]=errorResponse(ErrorCode.GeneralError,ex.getMessage,500)
错误响应
}
}
}
我知道在scala中,函数的最后一行是函数返回的唯一位置,那么如何从catch返回呢?原因是我想在BaseResponse[string]中使用不同的错误代码
谢谢!每当您有一个要传播到最外层作为结果的内部表达式时,您可以将其指定给外部表达式中的临时变量,或者使用
返回
。例如:
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 )
}
尽管第二种模式看起来毫无意义,但请记住,使用
返回退出方法并不总是显而易见的,尤其是在较长的方法中。因此,在某些情况下,第二种模式可以更清晰地阅读(特别是当您知道预期模式时).愚蠢的问题,但是你确定要在你的ValidateUpdateProductRequest
方法中抛出一个异常吗?可能是你传递的主catch
是因为另一个异常,例如在updateProduct
中……是的,我一步一步地对它进行了调试,我正在到达t的捕获线第二次尝试。但是函数不返回,它继续到ValdDeleTeTebug结果=产品TrestPosial.UpDeaType(…),然后因为产品为NULL而获得空引用,这是验证的一部分。我理解函数中间的返回不是“最佳实践”。甚至违背了scala的原则,所以我想我应该尽量避免it@ilansch-您应该编写尽可能干净清晰地解决问题的代码。这可能意味着使用返回
!请注意,有一种替代模式(我的第二个示例)可能具有优势。也许您也可以提供帮助:非常感谢。