问题
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 ?
Sample:
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))
}
}
I get error:
method updateProduct has return statement; needs result type
回答1:
When you use return
you must, as it says, use an explicit return type. Scala will not infer it for you.
So, for example:
def fails(i: Int) = return (i+1) // Doesn't compile
def works(i: Int): Int = return (i+1) // Does
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/*...*/)
).
来源:https://stackoverflow.com/questions/22381645/how-to-break-rest-controller-that-return-action-in-scala-play-framework