문제

I develop Rest API with scala and play framework.

In my product controller, I do validation of parameters received.
In case they fail from some reason, I would like to response with BadRequest in the middle of the function and not in the last line as scala works..
In the code below - Code continues running to the Ok line.. which is wrong, I want to return !

def getProduct(lang: String, t: String, ids: String) = Action {
 val productIdsList =  ids.split(",").toList 

 if (productIdsList.length.equals(1) && productIdsList(0).equals("")) //Validate input params are product Ids and not empty !
 {
    var errorResponse:ErrorResponse[String] = ErrorResponse(ErrorCode.GeneralError, "No products IDs", 500)
    BadRequest(Json.toJson(errorResponse))//maybe return BadRequest(Json.toJson(errorResponse) ??
 }              

 val results = productService.getProducts(GetProductsRequest(lang,t,productIdsList));
 Ok(Json.toJson(results)) 
 // TODO: handle error
}

If implemented as:

return BadRequest(...)

It reply with error:

"method getProduct has return statement; needs result type"  

I Understand this is bad practice, so what is the best practice for quitting the function without finishing it (and not throwing exceptions..)

도움이 되었습니까?

해결책

Just put an else branch, so there's nowhere to continue:

def getProduct(lang: String, t: String, ids: String) = Action {
 val productIdsList =  ids.split(",").toList 

 if (productIdsList.length.equals(1) && productIdsList(0).equals("")){ //Validate input params are product Ids and not empty !
    var errorResponse:ErrorResponse[String] = ErrorResponse(ErrorCode.GeneralError, "No products IDs", 500)
    BadRequest(Json.toJson(errorResponse))//maybe return BadRequest(Json.toJson(errorResponse) ??
 }else{
    val results = productService.getProducts(GetProductsRequest(lang,t,productIdsList));
    Ok(Json.toJson(results)) 
    // TODO: handle error
 }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top