2014-03-13 79 views
0

我有一個運行一些代碼的控制器,我在try/catch中包裝了一些代碼,並希望在捕獲期間中斷控制器運行並返回錯誤。
它不會返回,我如何將我的響應包裝在操作函數中?如何打破在Scala/Play框架中返回Action的REST控制器

樣品:

def updateProduct(productId:String,lang: String, t: String) = Action { 
request => 
    request.body.asJson.map { 
    json => 
    var product:Product=null 
    try 
    { 
     product = json.as[Product] 
    }   
    catch 
    { 
     case ex: Exception => { 
      val errorResponse:ErrorResponse[String] = ErrorResponse(ErrorCode.InvalidParameters, ex.getMessage, 500) 
      return InternalServerError(Json.toJson(errorResponse)) //Does not stop, 
      } 
    } 

    val response = productService.updateProduct(UpdateProductRequest(lang,t,productId,product)) 

    if (response.isError) 
    { 
     InternalServerError(Json.toJson(response)) 
    } 
    else 
    { 
     Ok(Json.toJson(response)) 
    }}.getOrElse { 
    Logger.warn("Bad json:" + request.body.asText.getOrElse("No data in body")) 
     var errorResponse:ErrorResponse[String] = ErrorResponse(ErrorCode.GeneralError, "Error processing request", 500) 
     errorResponse.addMessage("No data in body") 
     Ok(Json.toJson(errorResponse)) 
     } 
    } 

我得到錯誤:

method updateProduct has return statement; needs result type 

回答

3

當您使用return必須的,因爲它說,使用一個明確的返回類型。斯卡拉不會爲你推斷它。

因此,舉例來說:

def fails(i: Int) = return (i+1)  // Doesn't compile 
def works(i: Int): Int = return (i+1) // Does 

我不知道什麼OkInternalServerError常見的超是,但是這將是你以後。如果它是無用的類型,如AnyRef(即Object),則使用Either或等價物可能是一個好主意(即Left(InternalServerError/*...*/)Right(Ok/*...*/))。

+0

常見的超類型是'SimpleResult':http://www.playframework.com/documentation/2.2.x/api/scala/index.html#play.api.mvc.SimpleResult – Ryan

相關問題