Error handling
Handle expected HTTP failures with structured exceptions and keep unexpected application errors inside a consistent error-handling boundary.
Introduction
LykosJS provides an error-handling system for representing expected HTTP failures and handling unexpected application errors. Instead of manually constructing an HTTP error response in every route, you can throw an exception and let the framework's error-handling boundary process it.
The error system includes two exception classes:HttpError for simple HTTP errors andHttpException for structured exceptions with error codes, custom payloads, exposure rules, causes and stack options.
The framework also provides predefined exception classes for common HTTP statuses, along with isHttpException()for identifying structured HTTP exceptions safely.
How error handling works
When an error is thrown while a request is being processed, the HTTP server catches it and passes it to the error handler. The error handler decides which response to produce based on the error type.
1async findOne(userId: string) {2 const user = await this.db.findById(userId)3 4if(!user) {5 throw new NotFoundException('User not found')6}7 8return { user }9}In this example, the route throws a NotFoundExceptionwhen the requested user does not exist. The exception is not handled inside the route. It propagates to the HTTP server's error-handling boundary.
The server passes the thrown error to ErrorHandler.handle(), which converts recognized errors into an HTTP response.
ErrorHandler
ErrorHandler.handle(error) is the central error processing method. It accepts unknown because JavaScript allows throwing values that are not necessarily instances of Error.
1ErrorHandler.handle(error: unknown): ResponseThe current implementation handles errors using two branches:
- If the error is an instance of
HttpError, the handler returns a JSON response containing its message and uses itsstatusas the HTTP status. - For every other value, the handler logs the unexpected error on the server and returns a generic
500 Internal Server Errorresponse.
1// HttpError2{3 "error": "User not found"4}5 6// Unexpected error7{8 "error": "Internal Server Error"9}HttpError
HttpError is the basic HTTP error class. Use it when you need to associate an error message with an HTTP status without requiring a structured error code or additional payload.
1import { HttpError } from 'lykosjs'2 3throw new HttpError(404, 'User not found')Its constructor accepts two arguments:
status: number— the HTTP status code.message: string— the error message.
1class HttpError extends Error {2 constructor(3 public readonly status: number,4 message: string,5 )6}The class extends the native JavaScript Error. Its name is set to HttpError, and its status is exposed through the readonlystatus property.
When ErrorHandler.handle() receives anHttpError, it returns the following JSON structure:
1{2 "error": "User not found"3}The HTTP response status is taken fromerror.status. The currentErrorHandler does not add astatusCode or code property to this response body.
HttpException
HttpException is the structured HTTP exception class. It provides more control than HttpErrorby supporting a status code, machine-readable error code, custom response payload, exposure rules and optional error metadata.
1import { HttpException } from 'lykosjs'2 3throw new HttpException(4 409,5 'ACCOUNT_CONFLICT',6 {7 message: 'An account with this email already exists',8 field: 'email',9 },10)Its constructor accepts four arguments:
statusCode: number— the HTTP status code.code: string— a machine-readable error identifier.input: ErrorInput— a string or custom error payload.options?: ExceptionOptions— optional cause and stack configuration.
The exception extends the native Error class. Its name is set to the actual subclass name, or HttpException when instantiated directly.
ErrorInput
The ErrorInput type defines the supported input formats for structured exceptions.
1type ErrorResponse = Record<string, unknown>2 3type ErrorInput =4 | string5 | ErrorResponseYou can provide a simple message string or an object containing a message and additional properties.
1// String input2throw new NotFoundException('User not found')3 4// Object input5throw new NotFoundException({6 message: 'User not found',7 resource: 'user',8 resourceId: 'user_123',9})When an object is supplied, its additional properties are preserved in the exception's internal response payload. The message property is normalized so that it always contains a usable, non-blank string.
Message normalization
Structured exceptions normalize their input before creating the exception. This ensures that the resulting exception always has a usable message.
- A non-empty string is used as the message.
- An empty or whitespace-only string falls back to the exception's default message.
- When an object is provided, its valid
messageis used and its other properties are preserved. - If the object does not contain a usable message, the exception's default message is used.
- If the input is
nullorundefined, the default message is used.
1// Uses the supplied message2new NotFoundException('User does not exist')3 4// Uses the default message5new NotFoundException(' ')6 7// Uses the default message8new NotFoundException({9 message: '',10 resource: 'user',11})12 13// Preserves additional properties14new NotFoundException({15 message: 'User not found',16 resource: 'user',17})For predefined exceptions, the fallback message is supplied by that exception class. For a directly constructedHttpException, the fallback is its errorcode.
Structured exception properties
Every HttpException exposes the following readonly properties:
statusCode: number— the HTTP status associated with the exception.code: string— the machine-readable error code.response: ErrorResponse & { message: string }— the complete normalized payload supplied by the developer.expose: boolean— indicates whether the exception is considered safe to expose to the client.cause— inherited from the native Error class when a cause is provided.stack— the exception's stack trace, subject to its stack configuration.
1const error = new ConflictException({2 message: 'Email already exists',3 field: 'email',4})5 6error.statusCode7// 4098 9error.code10// 'CONFLICT'11 12error.message13// 'Email already exists'14 15error.expose16// true17 18error.response19// {20// message: 'Email already exists',21// field: 'email',22// }Predefined HTTP exceptions
LykosJS provides convenience exception classes for common HTTP error statuses. These classes extendHttpException and supply a fixed status code, machine-readable code and default message.
BadRequestException— 400,BAD_REQUEST.UnauthorizedException— 401,UNAUTHORIZED.ForbiddenException— 403,FORBIDDEN.NotFoundException— 404,NOT_FOUND.MethodNotAllowedException— 405,METHOD_NOT_ALLOWED.ConflictException— 409,CONFLICT.UnprocessableEntityException— 422,UNPROCESSABLE_ENTITY.TooManyRequestsException— 429,TOO_MANY_REQUESTS.InternalServerErrorException— 500,INTERNAL_SERVER_ERROR.ServiceUnavailableException— 503,SERVICE_UNAVAILABLE.
These classes accept the same ErrorInput and optional ExceptionOptions arguments. If no input is provided, the predefined default message is used.
1import {2 BadRequestException,3 UnauthorizedException,4 ForbiddenException,5 NotFoundException,6 MethodNotAllowedException,7 ConflictException,8 UnprocessableEntityException,9 TooManyRequestsException,10 InternalServerErrorException,11 ServiceUnavailableException,12} from 'lykosjs'13 14throw new BadRequestException('Invalid request')15throw new UnauthorizedException('Authentication required')16throw new ForbiddenException('Access denied')17throw new NotFoundException('User not found')18throw new ConflictException('Email already exists')Custom exception payloads
You can attach additional properties to an exception by passing an object as its input. These properties can provide useful structured information to API clients.
1throw new UnprocessableEntityException({2 message: 'Validation failed',3 errors: {4 email: ['Email is already in use'],5 username: ['Username is unavailable'],6 },7})For client errors, the structured payload is available through toJSON(), together with thestatusCode and code properties.
1{2 "message": "Validation failed",3 "errors": {4 "email": ["Email is already in use"],5 "username": ["Username is unavailable"]6 },7 "statusCode": 422,8 "code": "UNPROCESSABLE_ENTITY"9}Exception exposure
The expose property controls which exception information is included in the result oftoJSON().
Its value is determined automatically from the status code:
- Status codes from 400 through 499 set
exposetotrue. - Other status codes set
exposetofalse.
When an exception is exposed, toJSON() returns the normalized custom payload, along withstatusCode and code. The cause property is removed from that output.
When an exception is not exposed, toJSON()returns a safe generic message instead of the original custom payload.
1// A 4xx exception2const clientError = new ConflictException({3 message: 'Email already exists',4 field: 'email',5})6 7clientError.toJSON()8 9// {10// message: 'Email already exists',11// field: 'email',12// statusCode: 409,13// code: 'CONFLICT',14// }1// A 5xx exception2const serverError = new InternalServerErrorException({3 message: 'Database connection failed',4 database: 'primary',5})6 7serverError.toJSON()8 9// {10// message: 'Internal Server Error',11// statusCode: 500,12// code: 'INTERNAL_SERVER_ERROR',13// }toJSON()
HttpException.toJSON() produces a safe, serializable error object. It is useful when you need to serialize an exception without exposing its internal response payload for server errors.
1const error = new NotFoundException({2 message: 'User not found',3 resource: 'user',4})5 6const body = error.toJSON()The method returns an ErrorResponse object. Its output depends on the exception'sexpose property.
- Exposed exceptions preserve their normalized message and additional custom properties, then add
statusCodeandcode. - Non-exposed exceptions return the generic
Internal Server Errormessage with their status code and machine-readable code. - The
causeproperty is removed from exposed payloads.
ExceptionOptions
The optional ExceptionOptions object configures the original error cause and stack behavior.
1interface ExceptionOptions {2 cause?: unknown3 stack?: boolean4}cause
Use cause to preserve the original error that led to the HTTP exception. It is useful when converting a low-level error into an application-level HTTP exception without losing the underlying diagnostic information.
1try {2 await database.users.findById(userId)3} catch (cause) {4 throw new InternalServerErrorException(5 'Unable to retrieve user',6 { cause },7 )8}The original value is available through the nativeerror.cause property. It is intended for server-side diagnostics and is never included in the structured exception's client-facingtoJSON() output.
The cause can be any value because its TypeScript type isunknown. Do not assume that it is always an Error instance.
stack
Use the stack option to control whether the exception keeps its captured stack trace.
- If
stackistrue, the captured stack trace is retained. - If
stackisfalse, the stack is replaced with the exception'sName: messageheader. - If the option is omitted, 5xx exceptions retain their stack trace by default, while other statuses use the shortened stack.
1// Explicitly retain the stack2throw new ConflictException(3 'Operation failed',4 { stack: true },5)6 7// Explicitly shorten the stack8throw new InternalServerErrorException(9 'Internal operation failed',10 { stack: false },11)12 13// Default behavior:14// 5xx -> stack retained15// Other statuses -> shortened stackDisabling the stack avoids the lazy formatting of captured stack frames. It does not remove the exception's message, status code or other structured properties.
isHttpException()
Use isHttpException() to identify structured HTTP exceptions when the error value is typed asunknown.
1import { isHttpException } from 'lykosjs'2 3function inspectError(error: unknown) {4 if (isHttpException(error)) {5 console.log(error.statusCode)6 console.log(error.code)7 console.log(error.toJSON())8 return9 }10 11 console.error('Unexpected error', error)12}This function is a TypeScript type guard. When it returnstrue, TypeScript narrows the value toHttpException.
Internally, structured exceptions carry a private symbol brand created with Symbol.for(). The guard checks that brand instead of relying only oninstanceof. This allows the check to recognize branded exceptions across duplicated copies of the package.
HttpError versus HttpException
Both classes represent HTTP failures, but they expose different APIs and are handled differently by the current error handler.
HttpErrorusesstatusandmessage. The currentErrorHandlerrecognizes it usinginstanceof.HttpExceptionusesstatusCode,code, a structured response payload andtoJSON().- Predefined exceptions such as
NotFoundExceptionextendHttpException, notHttpError.
1// Basic HTTP error2throw new HttpError(404, 'User not found')3 4// Structured HTTP exception5throw new NotFoundException('User not found')Do not assume that the currentErrorHandler.handle() processes both classes identically. Its implementation explicitly checks onlyerror instanceof HttpError. Every other error, including a structured HttpException, follows its unexpected-error branch unless the error handler is extended to recognize it.
Unexpected errors
Unexpected errors include database failures, programming errors, failed external service calls and other exceptions that are not deliberately represented as HTTP errors.
1app.GET('/users', async () => {2 const users = await database.users.findMany()3 4 return Response.json(users)5})If the database operation throws, the error propagates to the HTTP server's error boundary. The currentErrorHandler logs the error and returns a generic 500 response.
Avoid returning internal exception messages, SQL queries, database connection strings, credentials or stack traces to API clients. Keep diagnostic details in server-side logs.
Throwing errors from asynchronous handlers
Errors thrown inside an asynchronous route handler reject its returned promise. The HTTP server awaits the handler and catches the resulting error.
1app.GET('/users/:id', async (ctx) => {2 const user = await users.find(ctx.params.id)3 4 if (!user) {5 throw new NotFoundException('User not found')6 }7 8 return Response.json(user)9})You do not need to wrap every expected exception in a local try/catch if you want it to reach the framework's error boundary.
Use a local try/catch when you need to recover from an error, translate it into another exception, or perform additional cleanup.
Preserving the original cause
When translating an error, pass the original error through the cause option. This keeps the relationship between the high-level HTTP exception and the low-level failure.
1try {2 await paymentProvider.charge(order)3} catch (cause) {4 throw new ServiceUnavailableException(5 'Payment provider is unavailable',6 { cause },7 )8}This example uses the original failure as diagnostic information while presenting a controlled exception message. The cause is not included in the structured exception's toJSON() output.
TypeScript mistakes
The error API uses distinct classes and property names. Understanding their types prevents common TypeScript mistakes.
Using the wrong status property
1const error = new HttpError(404, 'Not found')2 3// Correct4error.status5 6// Incorrect: HttpError does not define statusCode7error.statusCode1const error = new NotFoundException('Not found')2 3// Correct4error.statusCode5 6// Incorrect: HttpException does not define status7error.statusUsing isHttpException() for HttpError
1function handle(error: unknown) {2 if (isHttpException(error)) {3 // This branch only identifies HttpException.4 }5}6 7// Incorrect assumption:8// isHttpException(new HttpError(404, 'Not found'))9// is false.If you need to recognize both classes, check each type explicitly.
1function handle(error: unknown) {2 if (error instanceof HttpError) {3 console.log(error.status)4 return5 }6 7 if (isHttpException(error)) {8 console.log(error.statusCode)9 console.log(error.code)10 return11 }12 13 console.error(error)14}Passing an invalid exception payload
1// Incorrect: input must be a string or error object2new NotFoundException(404)3 4// Correct5new NotFoundException('User not found')6 7new NotFoundException({8 message: 'User not found',9 resource: 'user',10})Passing the wrong options position
1// Incorrect: the second argument is not the options object2new NotFoundException({3 cause: originalError,4})5 6// Correct: pass options as the second argument7new NotFoundException(8 'Unable to find user',9 { cause: originalError },10)Assuming cause is always an Error
1function inspectCause(error: HttpException) {2 const cause = error.cause3 4 // Incorrect: cause is unknown5 // console.log(cause.message)6 7 // Correct: narrow the value first8 if (cause instanceof Error) {9 console.log(cause.message)10 }11}Using response instead of toJSON()
1const error = new InternalServerErrorException({2 message: 'Database connection failed',3 connection: 'primary',4})5 6// Incorrect: may expose internal details7const body = error.response8 9// Correct: safe serialized representation10const body = error.toJSON()Assuming a thrown value is an Error
1try {2 throw 'Something failed'3} catch (error) {4 // error is unknown in strict TypeScript5 6 if (error instanceof Error) {7 console.error(error.message)8 } else {9 console.error('Non-Error value:', error)10 }11}Complete example
The following example shows a route throwing a structured exception, preserving a database error as its cause and allowing the HTTP server's error boundary to process it.
1import {2 NotFoundException,3 ServiceUnavailableException,4} from 'lykosjs'5 6app.GET('/users/:id', async (ctx) => {7 let user8 9 try {10 user = await users.find(ctx.params.id)11 } catch (cause) {12 throw new ServiceUnavailableException(13 'Unable to retrieve users',14 { cause },15 )16 }17 18 if (!user) {19 throw new NotFoundException({20 message: 'User not found',21 resource: 'user',22 resourceId: ctx.params.id,23 })24 }25 26 return Response.json(user)27})Best practices
- Use predefined exceptions when their status and meaning match the failure.
- Use
HttpErrorfor simple status-and-message errors when its handling behavior is sufficient. - Use structured
HttpExceptionsubclasses when you need error codes, custom payloads, exposure control or a preserved cause. - Keep error messages safe and meaningful for their intended audience.
- Preserve the original error through
causewhen translating lower-level failures. - Use
isHttpException()to narrow unknown structured exception values. - Use
toJSON()instead of exposing the internalresponsepayload. - Do not assume that
HttpErrorandHttpExceptionare interchangeable. - Let unexpected errors reach the framework's error boundary when no local recovery is required.