Responding with Errors
Patterns for answering a request with a response that represents a failure
Return a Response and skip the mapping entirely
Returning a Response object from a handler is passed straight through — no
header merge, no status validation. It's the most direct way to answer a
request that can't succeed:
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get('/profile', ctx => {
const token = ctx.request.headers.get('authorization')
if (token !== 'secret') {
return new Response('Unauthorized', { status: 401 })
}
return { user: 'Alice' }
})
app.listen()Set ctx.response.status and return a plain value
If you'd rather keep returning a plain object and let Arcton serialize it to
JSON, set the status on ctx.response before the handler returns:
import { Arcton } from '@arcton/core'
const app = Arcton()
app.post('/orders', ctx => {
ctx.response.status = 201
return { created: true }
})
app.listen()ctx.response.status can only be set before the response body finalizes —
inside the handler, or before await next() in a global or route middleware.
Once the body finalizes (the handler returns, a step short-circuits, or a
layer replaces the body after next()), ctx.response has become a real
Response, whose status has no setter — assigning to it throws
TypeError: Attempted to assign to readonly property.. Header mutation is
different: ctx.response.headers.set(...) / .append(...) keeps working
after await next() and still reaches the client.
import type { Middleware } from '@arcton/contracts'
import { Arcton } from '@arcton/core'
const timing: Middleware = async (ctx, next) => {
const start = performance.now()
await next()
ctx.response.headers.set(
'X-Response-Time',
`${(performance.now() - start).toFixed(2)}ms`
)
}
const app = Arcton()
app.use(timing)
app.get('/health', () => ({ status: 'ok' }))
app.listen()Catch a thrown error inside middleware
A middleware is a plain async function, so wrapping await next() in a
try/catch turns whatever the rest of the chain throws into a normal response:
import type { Middleware } from '@arcton/contracts'
import { Arcton } from '@arcton/core'
const catchErrors: Middleware = async (ctx, next) => {
try {
await next()
} catch (error) {
ctx.response.status = 500
return { error: error instanceof Error ? error.message : 'Unknown error' }
}
}
const app = Arcton()
app.use(catchErrors)
app.get('/risky', () => {
throw new Error('boom')
})
app.listen()Because the throw happens before the handler's own return value finalizes the
response, ctx.response.status is still writable when the catch block
runs.
For a single catch-all instead of a try/catch in every middleware, see Global error handler.
Throw a ready-made HttpError instead of hand-rolling one
Repeating ctx.response.status = ...; return {...} at every place a request
can fail adds up. @arcton/core exports HttpError plus an Http
namespace with a factory for each common status — Http.BadRequest,
Http.Unauthorized, Http.Forbidden, Http.NotFound,
Http.MethodNotAllowed, Http.Conflict, Http.Gone,
Http.UnprocessableEntity, Http.TooManyRequests,
Http.InternalServerError, Http.ServiceUnavailable — so the
status/message pairing lives in one place instead of at every throw site:
import { Arcton, Http } 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.listen()Each factory is a plain function, not a class — call it, don't new it. It
returns an HttpError (a subclass of Error) carrying:
status— the HTTP status code (404forHttp.NotFound)code— a stable, machine-readable tag ('NOT_FOUND') safe for a client to switch on, unlikemessagemessage— the status's reason phrase by default, overridable as the factory's first argumentbody— an optional second argument: the exact value to send back instead of the default{ code, message }
import { Http } from '@arcton/core'
throw Http.Conflict('Email already registered', { field: 'email' })throw Http.NotFound — the bare function reference, with no () — throws
the function itself, not an HttpError. A catch block checking
instanceof HttpError won't recognize it, and it reaches the adapter as an
undifferentiated 500 instead (see Uncaught errors).
Always call the factory.
On its own, throwing one of these is still an uncaught error. Catch it with
the same try/catch pattern as above, keyed off instanceof HttpError so the
status and body it carries drive the response:
import type { Middleware } from '@arcton/contracts'
import { Arcton, Http, HttpError } from '@arcton/core'
declare function findOrder(id: string): { id: string } | undefined
const catchHttpErrors: Middleware = async (ctx, next) => {
try {
await next()
} catch (err) {
if (err instanceof HttpError) {
ctx.response.status = err.status
return err.body ?? { code: err.code, message: err.message }
}
throw err
}
}
const app = Arcton()
app.use(catchHttpErrors)
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.listen()A status without a named factory still works — construct HttpError
directly: new HttpError(451, 'UNAVAILABLE_FOR_LEGAL_REASONS', 'Unavailable For Legal Reasons').
See HTTP errors for the full list of factories and
their default status/code/message.
Arcton's own responses
A few responses come from Arcton itself, not from your code:
- No route matches the request at all →
404with a JSON body shaped{"code":"NOT_FOUND","message":"Not Found"}, built directly fromHttp.NotFound()— computed once, not per request, and resolved without ever throwing (unlike a handler's ownthrow Http.NotFound(), it doesn't depend on a registered catch-all to become a response — see HTTP errors). - A route exists for the path but not for this method →
405with anAllowheader listing the methods that node does have (e.g.Allow: GET, POST). - A
params,queryorbodyschema rejects the request →400with a JSON body shaped{"issues":[{"message":"...","path":[...]}]}— see Validation errors. - The request's
Content-Typehas no parser registered for it →415with an empty body — see Body parsers. - A built-in parser can't parse the body (malformed JSON, for example) →
400with{"issues":[{"message":"Invalid request body"}]}.
See Response for the full mapping from a
handler's return value to a Response.