Given a case class with any require
case class Foo(id: Int, value: Int) {
require(value < 0 "value must be bigger than zero")
}
Is possible to throw this messages to http?
val routes = pathPrefix("foos") {
pathEnd {
post {
entity(as[Foo]) { foo =>
saveFoo(foo) match {
case Success(p) => {
complete(StatusCodes.Created)
}
case Failure(f) => {
println(f.getMessage) // unknown error
complete(BadRequest, f.getMessage)
}
}
}
}
}
The Akka-HTTP infrastructure will already convert all errors occurring during unmarshalling into a
400 (BadRequest)
error, and the exception message will be automatically used.With your same code I am getting that behaviour for free. Small changes I made:
the business logic error is now a
500
, to avoid confusionthe case class requirement is now consistent with the message (
>
is required instead of<
).