How to Map Domain Errors to HTTP Responses
In this guide, we take a small book-lending service whose business logic fails with typed domain errors, such as "book not found" or "book already on loan", and turn each error into the HTTP status code and body a client expects. By the end, you will have the same service written twice: once with plain Routes, where one Routes#handleError call maps every error, and once with an Endpoint, where each error is declared next to its status code and zio-http writes a JSON body for it.
We start with the shape most ZIO code already has, an effect that fails with a sealed trait, and map it on the routes. Then we move the same mapping into an endpoint declaration, which also puts the errors into the generated OpenAPI documentation.
The Problem
Business logic written with ZIO usually reports expected failures in the error channel, as a type such as IO[BookError, Book]. HTTP clients do not see Scala types, though: they see a status code and a body. Something has to decide that a missing book is 404 Not Found and that a book on loan is 409 Conflict, and the program does not compile until that decision is made, because Server.serve only accepts routes whose error type is Response or Nothing.
Without a single place for that decision, the mapping tends to spread. Each handler catches its own errors and builds its own response, so the same case BookNotFound(id) => ... line is copied into every handler that looks up a book, and the copies drift apart: one returns 404 with a message, another returns 400, a third returns 500 because someone called orDie to make the types line up. A client then gets different answers for the same failure depending on which URL it called, and adding a new error case means finding every copy.
zio-http gives this decision one home. Handlers keep failing with the domain error type, and either the routes or the endpoint declaration maps each error case to a response, once.
Prerequisites
The routes approach needs only zio-http. The endpoint approach also needs zio-schema's derivation module, which generates the Schema that encodes each error as JSON:
libraryDependencies ++= Seq(
"dev.zio" %% "zio-http" % "3.12.0",
"dev.zio" %% "zio-schema-derivation" % "1.9.2",
)
This guide assumes you can define routes and handlers. If not, start with Routes and Handler.
Model Domain Errors as a Sealed Trait
The service lends books. Looking up a book can fail because the book does not exist, and borrowing one can also fail because someone else has it. We model both failures as cases of one sealed trait, so every possible error is listed in one place and the compiler knows the full set:
import zio._
import zio.http._
case class Book(id: Int, title: String)
sealed trait BookError
case class BookNotFound(id: Int) extends BookError
case class BookOnLoan(id: Int) extends BookError
The repository stands in for a database. Book 1 is available, book 2 is on loan, and any other id does not exist:
object BookRepo {
private val books = Map(
1 -> Book(1, "Zionomicon"),
2 -> Book(2, "Functional Programming in Scala"),
)
private val onLoan = Set(2)
def find(id: Int): IO[BookNotFound, Book] =
ZIO.fromOption(books.get(id)).orElseFail(BookNotFound(id))
def borrow(id: Int): IO[BookError, Book] =
find(id).flatMap { book =>
if (onLoan.contains(id)) ZIO.fail(BookOnLoan(id))
else ZIO.succeed(book)
}
}
BookRepo.find fails only with BookNotFound, while BookRepo.borrow can fail with either case, so its error type is the whole BookError trait. Nothing in the repository knows about HTTP; that stays true for the rest of the guide.
Map Errors on Routes with Routes#handleError
We first write the routes so that each handler returns the repository's effect as it is. The handlers succeed with a Response and fail with BookError, so the routes have the type Routes[Any, BookError]:
val routes: Routes[Any, BookError] =
Routes(
Method.GET / "books" / int("id") -> handler { (id: Int, _: Request) =>
BookRepo.find(id).map(book => Response.text(book.title))
},
Method.POST / "books" / int("id") / "borrow" -> handler { (id: Int, _: Request) =>
BookRepo.borrow(id).map(book => Response.text(s"You borrowed ${book.title}"))
},
)
Routes#handleError takes a function from the error type to a Response and applies it to every route. Because BookError is sealed, the function is one pattern match with one case per error:
val app: Routes[Any, Response] =
routes.handleError {
case BookNotFound(id) => Response.notFound(s"Book $id does not exist")
case BookOnLoan(id) => Response.error(Status.Conflict, s"Book $id is on loan")
}
Routes#handleError returns Routes[Any, Nothing]: no error is left unhandled. We annotate the value as Routes[Any, Response], which Nothing satisfies, and Server.serve accepts either error type. Response.notFound and Response.error both build a response with an error status and the given text, HTML-escaped, as the body.
Because the match is over a sealed trait, the compiler checks it. If we add a third BookError case and forget to map it, Scala 2.13 warns match may not be exhaustive at the routes.handleError call, so the new error cannot silently fall through.
The routes are now ready to serve:
object BookServer extends ZIOAppDefault {
def run = Server.serve(app).provide(Server.default)
}
With the server running, each request gets the status code of its error case and the message as a plain body:
$ curl -i http://localhost:8080/books/3
HTTP/1.1 404 Not Found
content-length: 21
Book 3 does not exist
$ curl -i -X POST http://localhost:8080/books/2/borrow
HTTP/1.1 409 Conflict
content-length: 17
Book 2 is on loan
$ curl -i -X POST http://localhost:8080/books/1/borrow
HTTP/1.1 200 OK
content-type: text/plain
content-length: 23
You borrowed Zionomicon
The error responses have no content-type header: Response.error with a String message sets none. If your clients expect JSON error bodies, build them in the mapping function, or let an endpoint do it, as the next section shows.
Routes#handleError receives only the typed failures from the error channel. A defect, such as an exception thrown inside ZIO.succeed or a ZIO.die, skips your function and stays unhandled. To map defects as well, use Routes#handleErrorCause, which receives the whole Cause. To take the request into account, for example to log its path, use Routes#handleErrorRequest.
Runnable version, with the model from Model.scala and the routes joined into one server: Step4RoutesHandleErrorExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
package example.domainerrors
import zio._
case class Book(id: Int, title: String)
sealed trait BookError
case class BookNotFound(id: Int) extends BookError
case class BookOnLoan(id: Int) extends BookError
object BookRepo {
private val books = Map(
1 -> Book(1, "Zionomicon"),
2 -> Book(2, "Functional Programming in Scala"),
)
private val onLoan = Set(2)
def find(id: Int): IO[BookNotFound, Book] =
ZIO.fromOption(books.get(id)).orElseFail(BookNotFound(id))
def borrow(id: Int): IO[BookError, Book] =
find(id).flatMap { book =>
if (onLoan.contains(id)) ZIO.fail(BookOnLoan(id))
else ZIO.succeed(book)
}
}
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file Model.scala
// Run from this folder: scala-cli run Step4RoutesHandleErrorExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.domainerrors.Step4RoutesHandleErrorExample"
package example.domainerrors
import zio._
import zio.http._
/**
* Map Domain Errors to HTTP Responses — Map Errors on Routes with handleError
*
* Handlers fail with the domain error type `BookError`, and one `handleError`
* call on the routes turns each error case into a status code and a body.
*/
object Step4RoutesHandleErrorExample extends ZIOAppDefault {
val routes: Routes[Any, BookError] =
Routes(
Method.GET / "books" / int("id") -> handler { (id: Int, _: Request) =>
BookRepo.find(id).map(book => Response.text(book.title))
},
Method.POST / "books" / int("id") / "borrow" -> handler { (id: Int, _: Request) =>
BookRepo.borrow(id).map(book => Response.text(s"You borrowed ${book.title}"))
},
)
val app: Routes[Any, Response] =
routes.handleError {
case BookNotFound(id) => Response.notFound(s"Book $id does not exist")
case BookOnLoan(id) => Response.error(Status.Conflict, s"Book $id is on loan")
}
def run = Server.serve(app).provide(Server.default)
}
Declare Errors on an Endpoint with Endpoint#outErrors
With Routes, the mapping lives in a function, so only the running server knows which status codes a route can return. An Endpoint declares them instead: each error case gets an HttpCodec that pairs it with a status code and encodes it as the body. zio-http then uses those codecs to write the response, to decode it in a generated client, and to describe it in the OpenAPI documentation.
The codecs need a Schema for the success type and for each error case. We derive them:
import zio.schema.{DeriveSchema, Schema}
implicit val bookSchema: Schema[Book] = DeriveSchema.gen
implicit val notFoundSchema: Schema[BookNotFound] = DeriveSchema.gen
implicit val onLoanSchema: Schema[BookOnLoan] = DeriveSchema.gen
Endpoint#outErrors takes the sealed trait as its type parameter and one HttpCodec.error per case. Each HttpCodec.error[E](status) says: when the error is an E, respond with status and E encoded as the body. The endpoint's error type becomes BookError:
import zio.http.codec._
import zio.http.endpoint._
val borrowBook: Endpoint[Int, Int, BookError, Book, AuthType.None] =
Endpoint(Method.POST / "books" / int("id") / "borrow")
.out[Book]
.outErrors[BookError](
HttpCodec.error[BookNotFound](Status.NotFound),
HttpCodec.error[BookOnLoan](Status.Conflict),
)
The implementation is the repository call and nothing else. Endpoint#implement takes a function that may fail with the endpoint's error type, and returns a route whose errors are already handled, so there is no Routes#handleError call:
val endpointApp: Routes[Any, Response] =
Routes(borrowBook.implement(id => BookRepo.borrow(id)))
We serve it the same way as before:
object BookEndpointServer extends ZIOAppDefault {
def run = Server.serve(endpointApp).provide(Server.default)
}
This time every response, successful or not, carries a JSON body and a content-type header:
$ curl -i -X POST http://localhost:8080/books/3/borrow
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 8
{"id":3}
$ curl -i -X POST http://localhost:8080/books/2/borrow
HTTP/1.1 409 Conflict
content-type: application/json
content-length: 8
{"id":2}
$ curl -i -X POST http://localhost:8080/books/1/borrow
HTTP/1.1 200 OK
content-type: application/json
content-length: 29
{"id":1,"title":"Zionomicon"}
The body is the error case class itself, encoded with its Schema. To send more to the client, such as a message, add fields to the case class.
You can also declare the errors one at a time with Endpoint#outError. Each call adds one case, and two calls give the endpoint an Either error type, with the later call on the Left side. The handler then has to wrap each failure in Left or Right, which is why a sealed trait with Endpoint#outErrors is easier to work with:
val borrowBookEither: Endpoint[Int, Int, Either[BookOnLoan, BookNotFound], Book, AuthType.None] =
Endpoint(Method.POST / "books" / int("id") / "borrow")
.out[Book]
.outError[BookNotFound](Status.NotFound)
.outError[BookOnLoan](Status.Conflict)
The two approaches map the same errors; they differ in where the mapping lives and what it gives you beyond the response:
| Concern | Routes#handleError | Endpoint#outErrors |
|---|---|---|
| Where the mapping lives | A function on the routes | The endpoint declaration |
| Response body | Whatever the function builds | The error case encoded with its Schema |
| Extra setup | None | A Schema per error case |
| Errors in OpenAPI documentation | No | Yes |
| Errors decoded by a client | No | Yes, through the same endpoint |
Runnable version, with the model from Model.scala and the endpoint served as one program: Step5EndpointOutErrorsExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using dep "dev.zio::zio-schema-derivation:1.9.2"
//> using file Model.scala
// Run from this folder: scala-cli run Step5EndpointOutErrorsExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.domainerrors.Step5EndpointOutErrorsExample"
package example.domainerrors
import zio._
import zio.schema.{DeriveSchema, Schema}
import zio.http._
import zio.http.codec._
import zio.http.endpoint._
/**
* Map Domain Errors to HTTP Responses — Declare Errors on an Endpoint with
* outErrors
*
* The endpoint declares one error codec per `BookError` case, so the handler
* fails with `BookError` and zio-http writes the status code and a JSON body.
*/
object Step5EndpointOutErrorsExample extends ZIOAppDefault {
implicit val bookSchema: Schema[Book] = DeriveSchema.gen
implicit val notFoundSchema: Schema[BookNotFound] = DeriveSchema.gen
implicit val onLoanSchema: Schema[BookOnLoan] = DeriveSchema.gen
val borrowBook: Endpoint[Int, Int, BookError, Book, AuthType.None] =
Endpoint(Method.POST / "books" / int("id") / "borrow")
.out[Book]
.outErrors[BookError](
HttpCodec.error[BookNotFound](Status.NotFound),
HttpCodec.error[BookOnLoan](Status.Conflict),
)
val borrowBookEither: Endpoint[Int, Int, Either[BookOnLoan, BookNotFound], Book, AuthType.None] =
Endpoint(Method.POST / "books" / int("id") / "borrow")
.out[Book]
.outError[BookNotFound](Status.NotFound)
.outError[BookOnLoan](Status.Conflict)
val endpointApp: Routes[Any, Response] =
Routes(borrowBook.implement(id => BookRepo.borrow(id)))
def run = Server.serve(endpointApp).provide(Server.default)
}
Running the Examples
All runnable code from this guide is in zio-http-example/src/main/scala/example/domainerrors/. Run any file from that folder with scala-cli run <File>.scala, or from the repository root with sbt "zioHttpExample/runMain example.domainerrors.<ObjectName>". Each example starts a server on port 8080; send it the curl requests above.
Going Further
- Routes lists every error-handling method on
Routes, including the ones that receive theCauseor theRequest. - Endpoint covers error outputs in more depth, and its OpenAPI section shows how the declared errors appear in the generated documentation.
- Response lists the constructors for building error responses by hand.
- Part 5: Error Responses of the Build Your First REST API tutorial introduces typed errors and JSON error bodies at a beginner's pace.
- Handler shows the
Handleroperators, such asHandler#mapError, for mapping errors in a single handler before it becomes a route.