繁体   English   中英

如何打破在 Scala/Play 框架中返回 Action 的 REST 控制器

[英]How to break REST controller that return Action in Scala/Play framework

我有一个运行一些代码的控制器,我在 try/catch 中包装了一些代码,并希望在 catch 期间中断控制器运行并返回错误。
它没有返回,如何根据需要将我的响应包装在动作函数中?

样本:

 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

当您使用return时,正如它所说,您必须使用显式返回类型。 Scala 不会为您推断它。

因此,例如:

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/*...*/) )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM