Global Error Handler
Catch every otherwise-uncaught error in one place with app.onError()
Uncaught errors reach the runtime adapter as a bare
500 unless something catches them first. app.onError() registers a single
handler that catches any of those — from a provider, a middleware, a body
parser, or the route handler itself — before it gets that far:
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/risky', () => {
throw new Error('boom')
})
app.onError((err, ctx) => {
console.error(err)
return { error: 'Something went wrong' }
})
app.listen()A request to /risky now answers with the handler's own response instead of
the adapter's generic 500 text. onError() is opt-in — an app that never
calls it keeps behaving exactly like Uncaught errors
describes.
The status defaults to 500
If the handler doesn't set ctx.response.status itself, the response
defaults to 500. Set it explicitly to answer with something else — for
example, narrowing on HttpError to reuse the status it already carries:
import { Arcton, Http, HttpError } from '@arcton/core'
declare function findOrder(id: string): { id: string } | undefined
const app = Arcton()
app.get('/orders/:id', ctx => {
const order = findOrder(ctx.params.id)
if (!order) throw Http.NotFound(`Order ${ctx.params.id} not found`)
return order
})
app.onError((err, ctx) => {
if (err instanceof HttpError) {
ctx.response.status = err.status
return err.body ?? { code: err.code, message: err.message }
}
return { code: 'INTERNAL_SERVER_ERROR', message: 'Internal Server Error' }
})
app.listen()A status set earlier in the request — by a middleware that ran before the
throw, say — is left alone if the handler never touches ctx.response.status
itself; the 500 default only fills in when nothing set a status at all.
Like any handler, onError() can return a plain value (mapped through the
usual Response rules) or a Response object
directly, which is sent through unchanged.
Validation errors go through it too
A failed params, query or body schema — or a body Arcton can't parse at
all — reaches onError() as a ValidationError: an HttpError subclass whose
issues are exactly what the schema library returned. An unsupported body
Content-Type arrives as an HttpError with status 415.
import { Arcton, ValidationError } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users', {
body: v.object({ email: v.pipe(v.string(), v.email()) }),
handler: ctx => ({ created: ctx.body })
})
app.onError((err, ctx) => {
if (err instanceof ValidationError) {
return { error: 'Invalid request', issues: err.issues }
}
return { error: 'Something went wrong' }
})
app.listen()The response above is a 400 even though the handler never set a status: for
these two request errors the status defaults to their own (400, 415)
instead of 500.
Validation errors are answered right where they happen, so middleware wrapping
the route — CORS, request logging — still sees a normal response after
await next(). Any other thrown error unwinds through that middleware first.
Returning nothing declines the error
onError() handles an error by returning a value or a Response. If it
returns nothing, Arcton's default applies instead: a validation error answers
400 with the issues body, an
unsupported Content-Type answers an empty 415, and any other error
propagates to the adapter exactly as it would with no handler registered. That
makes onError() a fine place to log everything and only take over the
responses you care about.
Runs for the 404/405 fallback too
Global middleware runs even when nothing matches
the request, so onError() covers a throw there as well:
import { Arcton } from '@arcton/core'
declare function logRequest(request: Request): void
const app = Arcton()
app.use(async (ctx, next) => {
logRequest(ctx.request) // throws if the logger is down
await next()
})
app.onError((err, ctx) => ({ error: 'Something went wrong' }))
app.listen()It's a single, top-level handler
Only one onError() handler exists per app — registering a second one
replaces the first — and only the instance whose own listen() ends up
serving the request is ever consulted. If you build part of your app as a
separate module and mount it with app.use(module), an onError() call on
that module has no effect; modules compose routes, middleware, and
providers into the mounting app, not an independent error boundary.
For a boundary scoped to one section of the app, wrap next() in a
try/catch inside a scoped middleware instead —
see Catch a thrown error inside middleware.
The two compose fine together: a scoped try/catch handles what it recognizes
and rethrows anything else, which then reaches onError() as the final
catch-all.
If the onError() handler itself throws, that error isn't passed back
in — it propagates the same way an uncaught error would with no handler
registered at all.