如何破坏在Scala/Play框架中返回Action的REST控制器 [英] How to break REST controller that return Action in Scala/Play framework
问题描述
我有一个运行一些代码的控制器,我在try/catch中包装了一些代码,希望中断在catch期间运行的控制器并返回错误.
它不会返回,我如何根据需要将响应包装在动作函数中?
I have a controller that run some code, I wrap some code in try/catch and wish to break the controller run during catch and return the error.
It does not return, How can i wrap my response in action function as required ?
示例:
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不会为您推断出来.
When you use return
you must, as it says, use an explicit return type. Scala will not infer it for you.
例如,
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/*...*/)
)可能是个好主意.
I am not sure what the common supertype of Ok
and InternalServerError
is, but that would be what you're after. If it's an unhelpful type like AnyRef
(i.e. Object
), using Either
or the equivalent might be a good idea (i.e. Left(InternalServerError/*...*/)
, Right(Ok/*...*/)
).
这篇关于如何破坏在Scala/Play框架中返回Action的REST控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!