Skip to main content

Part 5: Error Responses

Our API works for well-behaved clients, but its failures are hard to understand. An unknown book and a broken request body both answer with an empty body, and ?limit=abc is silently ignored. In this part, we make every failure explicit: each one gets the right status code and a JSON body that explains what went wrong.

The key idea is that in ZIO, a failure is a value. An effect of type ZIO[R, E, A] either succeeds with an A or fails with an E, and the compiler tracks E for us. ZIO HTTP builds on this: a handler may fail, but only with a Response. So handling an error always means the same thing: turning a typed failure into a Response.

1. Give Errors a JSON Body​

Clients of a JSON API expect JSON, even when something goes wrong. Let's define the shape of an error body, with a schema like our other types, and place it below NewBook:

import zio._
import zio.http._
import zio.schema.{DeriveSchema, Schema}

// Book and NewBook, with their schemas, are unchanged from part 3.
final case class Book(id: Int, title: String, author: String, year: Int)
object Book { implicit val schema: Schema[Book] = DeriveSchema.gen[Book] }
final case class NewBook(title: String, author: String, year: Int)
object NewBook { implicit val schema: Schema[NewBook] = DeriveSchema.gen[NewBook] }

final case class ApiError(message: String)

object ApiError {
implicit val schema: Schema[ApiError] = DeriveSchema.gen[ApiError]
}

Next, add a second helper below jsonResponse, inside object BooksApp (the snippet repeats jsonResponse for context, so add only errorResponse):

def jsonResponse[A](status: Status, value: A)(implicit schema: Schema[A]): Response =
Response(status, body = Body.json(value)).contentType(MediaType.application.json)

def errorResponse(status: Status, message: String): Response =
jsonResponse(status, ApiError(message))

errorResponse(Status.NotFound, "No book with id 42") builds a 404 Not Found response whose body is {"message":"No book with id 42"}. Because it reuses jsonResponse, the error also carries the content-type: application/json header.

2. Make "Not Found" a Typed Error​

Until now, BookRepo#get returned UIO[Option[Book]], and every handler had to remember that None means "not found". Let's say it in the type instead. A BookNotFound value describes the failure, and get now returns IO[BookNotFound, Book]: an effect that either succeeds with the book or fails with BookNotFound. Update the service:

final case class BookNotFound(id: Int)

trait BookRepo {
def all: UIO[List[Book]]
def get(id: Int): IO[BookNotFound, Book]
def add(newBook: NewBook): UIO[Book]
}

In InMemoryBookRepo, only InMemoryBookRepo#get changes:

final case class InMemoryBookRepo(books: Ref[Map[Int, Book]]) extends BookRepo {

def all: UIO[List[Book]] =
books.get.map(_.values.toList.sortBy(_.id))

def get(id: Int): IO[BookNotFound, Book] =
books.get.flatMap(current => ZIO.fromOption(current.get(id)).orElseFail(BookNotFound(id)))

def add(newBook: NewBook): UIO[Book] =
books.modify { current =>
val id = if (current.isEmpty) 1 else current.keys.max + 1
val book = Book(id, newBook.title, newBook.author, newBook.year)
(book, current + (id -> book))
}
}

ZIO.fromOption(current.get(id)) turns the Option into an effect that succeeds with the book or fails when there is none, and ZIO#orElseFail(BookNotFound(id)) names that failure.

Now the handler for GET /books/{id} must deal with both outcomes. ZIO#mapBoth maps the failure and the success at once: the failure becomes a 404 error response, and the book becomes a 200 JSON response:

Method.GET / "books" / int("id") -> handler { (id: Int, _: Request) =>
ZIO
.serviceWithZIO[BookRepo](_.get(id))
.mapBoth(
notFound => errorResponse(Status.NotFound, s"No book with id ${notFound.id}"),
book => jsonResponse(Status.Ok, book),
)
}

Here is the payoff of typed errors: the compiler now makes sure we handle "not found". Try replacing ZIO#mapBoth with ZIO#map(book => jsonResponse(Status.Ok, book)). The handler would then fail with a BookNotFound instead of a Response, and the program no longer compiles, because Routes[BookRepo, Response] only accepts handlers that fail with a Response.

3. Reject a Malformed Query Parameter​

In part 2, we read limit with Request#queryOrElse, which falls back to 10 when the value is missing and also when it is not a number. We want to tell those two cases apart: a missing limit is fine, but limit=abc is a mistake the client should hear about.

Request#query does exactly that. Asked for an Option[Int], it returns an Either: Right(None) when limit is missing, Right(Some(2)) for limit=2, and Left(...) with a description of the problem for limit=abc. The new GET /books handler turns the Left into a 400 Bad Request:

Method.GET / "books" -> handler { (req: Request) =>
val author = req.queryParam("author")
for {
limit <- ZIO
.fromEither(req.query[Option[Int]]("limit"))
.orElseFail(errorResponse(Status.BadRequest, "limit must be a whole number"))
books <- ZIO.serviceWithZIO[BookRepo](_.all)
matching = books.filter(book => author.forall(_ == book.author)).take(limit.getOrElse(10))
} yield jsonResponse(Status.Ok, matching)
}

Line by line:

  • req.query[Option[Int]]("limit") reads and converts limit, returning an Either.
  • ZIO.fromEither(...) turns the Either into an effect that fails with the Left or succeeds with the Right.
  • ZIO#orElseFail(errorResponse(Status.BadRequest, ...)) replaces that failure with a 400 JSON error response, so the effect now fails with a Response.
  • limit.getOrElse(10) keeps the default of 10 when limit is missing.

4. Explain a Bad Request Body​

The POST /books route already answers 400 Bad Request when the body is not a valid NewBook, but with an empty body. The fix is a one-line change: pass an errorResponse to ZIO#orElseFail instead of Response.badRequest:

Method.POST / "books" -> handler { (req: Request) =>
for {
newBook <- req.body
.asJson[NewBook]
.orElseFail(errorResponse(Status.BadRequest, "body must be a JSON book with title, author and year"))
book <- ZIO.serviceWithZIO[BookRepo](_.add(newBook))
} yield jsonResponse(Status.Created, book)
}

5. Run It​

Restart the server with sbt run and ask for a book that does not exist:

curl -i localhost:8080/books/42

The 404 now explains itself:

HTTP/1.1 404 Not Found
content-type: application/json
content-length: 32

{"message":"No book with id 42"}

Next, send a limit that is not a number:

curl -i "localhost:8080/books?limit=abc"

Instead of silently ignoring it, the server answers 400 Bad Request:

HTTP/1.1 400 Bad Request
content-type: application/json
content-length: 42

{"message":"limit must be a whole number"}

Then send an incomplete book:

curl -i -X POST localhost:8080/books -d '{"title":"Snow Crash"}'

The client learns what the body must contain:

HTTP/1.1 400 Bad Request
content-type: application/json
content-length: 66

{"message":"body must be a JSON book with title, author and year"}

Valid requests behave as before. For example, limit=2 still returns the first two books:

curl "localhost:8080/books?limit=2"

The server answers with two books:

[{"id":1,"title":"Dune","author":"Frank Herbert","year":1965},{"id":2,"title":"Neuromancer","author":"William Gibson","year":1984}]
note

GET /books/abc still answers 404 Not Found with an empty body. That request never reaches our handler: no route pattern matches it, so ZIO HTTP answers on its own.

This is the finished app. Its complete source is below.

The complete BooksApp.scala at the end of part 5: the finished app
zio-http-example-rest-api-tutorial/src/main/scala/example/restapi/BooksApp.scala
//> using scala 2.13.18
//> using dep dev.zio::zio-http:3.12.0
// Run from this folder: scala-cli run BooksApp.scala
// Or from zio-http-example-rest-api-tutorial: sbt "runMain example.restapi.BooksApp"

package example.restapi

import zio._
import zio.http._
import zio.schema.{DeriveSchema, Schema}

/**
* Build Your First REST API — Part 5: Error Responses (the finished app)
*
* Turns every failure into a JSON error response: an unknown book id becomes a
* 404, and a malformed `limit` query parameter or request body becomes a 400.
*/
final case class Book(id: Int, title: String, author: String, year: Int)

object Book {
implicit val schema: Schema[Book] = DeriveSchema.gen[Book]
}

final case class NewBook(title: String, author: String, year: Int)

object NewBook {
implicit val schema: Schema[NewBook] = DeriveSchema.gen[NewBook]
}

final case class ApiError(message: String)

object ApiError {
implicit val schema: Schema[ApiError] = DeriveSchema.gen[ApiError]
}

final case class BookNotFound(id: Int)

trait BookRepo {
def all: UIO[List[Book]]
def get(id: Int): IO[BookNotFound, Book]
def add(newBook: NewBook): UIO[Book]
}

final case class InMemoryBookRepo(books: Ref[Map[Int, Book]]) extends BookRepo {

def all: UIO[List[Book]] =
books.get.map(_.values.toList.sortBy(_.id))

def get(id: Int): IO[BookNotFound, Book] =
books.get.flatMap(current => ZIO.fromOption(current.get(id)).orElseFail(BookNotFound(id)))

def add(newBook: NewBook): UIO[Book] =
books.modify { current =>
val id = if (current.isEmpty) 1 else current.keys.max + 1
val book = Book(id, newBook.title, newBook.author, newBook.year)
(book, current + (id -> book))
}
}

object InMemoryBookRepo {

val initialBooks: List[Book] =
List(
Book(1, "Dune", "Frank Herbert", 1965),
Book(2, "Neuromancer", "William Gibson", 1984),
Book(3, "Count Zero", "William Gibson", 1986),
)

val layer: ULayer[BookRepo] =
ZLayer.fromZIO(
Ref.make(initialBooks.map(book => book.id -> book).toMap).map(InMemoryBookRepo(_)),
)
}

object BooksApp extends ZIOAppDefault {

def jsonResponse[A](status: Status, value: A)(implicit schema: Schema[A]): Response =
Response(status, body = Body.json(value)).contentType(MediaType.application.json)

def errorResponse(status: Status, message: String): Response =
jsonResponse(status, ApiError(message))

val routes: Routes[BookRepo, Response] =
Routes(
Method.GET / "health" -> handler(Response.text("OK")),
Method.GET / "books" -> handler { (req: Request) =>
val author = req.queryParam("author")
for {
limit <- ZIO
.fromEither(req.query[Option[Int]]("limit"))
.orElseFail(errorResponse(Status.BadRequest, "limit must be a whole number"))
books <- ZIO.serviceWithZIO[BookRepo](_.all)
matching = books.filter(book => author.forall(_ == book.author)).take(limit.getOrElse(10))
} yield jsonResponse(Status.Ok, matching)
},
Method.GET / "books" / int("id") -> handler { (id: Int, _: Request) =>
ZIO
.serviceWithZIO[BookRepo](_.get(id))
.mapBoth(
notFound => errorResponse(Status.NotFound, s"No book with id ${notFound.id}"),
book => jsonResponse(Status.Ok, book),
)
},
Method.POST / "books" -> handler { (req: Request) =>
for {
newBook <- req.body
.asJson[NewBook]
.orElseFail(errorResponse(Status.BadRequest, "body must be a JSON book with title, author and year"))
book <- ZIO.serviceWithZIO[BookRepo](_.add(newBook))
} yield jsonResponse(Status.Created, book)
},
)

def run = Server.serve(routes).provide(Server.default, InMemoryBookRepo.layer)
}

Recap​

In this part, we treated failures as typed values. BookRepo#get now fails with BookNotFound, Request#query reports a malformed query parameter as a Left, and in each handler ZIO#mapBoth or ZIO#orElseFail turns the failure into a Response with the right status code and a JSON ApiError body. Because routes only accept handlers that fail with a Response, the compiler reminds us whenever a failure is left unhandled.

In Part 6: Your First Test, we check all of this automatically, with tests that call the routes without starting a server.