Error handling
error is called when an error is thrown.
It accepts context similar to a handler, with an error property containing the thrown error. Use instanceof to check its class.
import { Elysia, NotFound } from 'elysia'
.onError(({ error, status }) => {
if(error instanceof NotFound)
return 'uhe~ are you lost?'
return status(418, "My bad! But I'm cute so you'll forgive me, right?")
You can return a status to override the default error status.
Custom error
Register an error class with .onError(ErrorClass, handler) to handle that type:
import { Elysia } from 'elysia'
class NicheError extends Error {
constructor(message: string) {
.onError(NicheError, ({ error, status }) => {
return status(418, "We have no idea how you got here")
throw new NicheError('Custom error message')
The handler receives an error typed as NicheError, so its properties are available with autocomplete.
Error status code
You can also provide a custom status code by adding a status property to class:
import { Elysia } from 'elysia'
class NicheError extends Error {
constructor(message: string) {
Elysia will use this status code if the error is thrown, see Custom status code.
Error response
Return a response from the class handler to choose the body and status:
import { Elysia } from 'elysia'
class NicheError extends Error {
.onError(NicheError, ({ error, status }) =>
status(error.status, { message: error.message })
throw new NicheError('Custom error message')
See Class error handlers.
Assignment
Let’s try to extend Elysia’s context.