How to throw messages to http response from case class require?

243 views Asked by At

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)
            }
          }
        }
      }
    } 
1

There are 1 answers

2
Stefano Bonetti On

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 confusion

  • the case class requirement is now consistent with the message (> is required instead of <).


  case class Foo(id: Int, value: Int) {
    require(value > 0, "value must be bigger than zero")
  }

  def saveFoo(foo: Foo): Try[Unit] = Success(())

  val route = 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(StatusCodes.InternalServerError, f.getMessage)
            }
          }
        }
      }
    }
  }