Pergunta

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..)

Foi útil?

Solução

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
 }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top