You can use require
inside scope of complete directive
(path("stats") & parameter("idsParam")) { idsParam =>
complete {
require(idsParam.length > 1)
val ids = idsParam.split(",").map(v => CaseId(v).value)
DBManager.getArticleStats(ids).map { case (id, stats) => IdWithValue(CaseId(id), stats) }
}
}
that handles yours POST request.
And typically I have custom exception handler that wraps all exceptions into format that my API client expects such as json. require
throws IllegalArgumentException
so let's handle it in special way if we want to.
protected implicit def myExceptionHandler =
ExceptionHandler {
case ex: IllegalArgumentException => ctx => {
val cause = ex.getCause
ex.printStackTrace()
ctx.complete(StatusCodes.InternalServerError, ErrorResponse(ex.code, ex))
}
case ex: Throwable => ctx =>
logger.warning("Request {} could not be handled normally", ctx.request)
ex.printStackTrace()
ctx.complete(StatusCodes.InternalServerError, ErrorResponse(StatusCodes.InternalServerError.intValue, ex))
}
where ErrorResponse
is my case class that is being serialized to json using spray-json