[英]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
我不確定Ok
和InternalServerError
的常見超類型是什么,但這就是您所追求的。 如果它是一個無用的類型,如AnyRef
(即Object
),則使用Either
或等效的可能是一個好主意(即Left(InternalServerError/*...*/)
, Right(Ok/*...*/)
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.