Exception

The Exception class extends native Error with HTTP status codes and optional data payload. It provides a response getter for converting errors into Res objects, making it ideal for consistent error handling across your application.

Contents
  1. Usage
  2. Constructor Parameters
  3. Properties
  4. Methods

Usage

Throwing errors in routes

import { C } from "@ozanarslan/corpus";

new C.Route("/users/:id", (c) => {
	const user = findUser(c.params.id);

	if (!user) {
		throw new C.Exception("User not found", C.Status.NOT_FOUND);
	}

	return user;
});

With custom data payload

new C.Route("/validate", (c) => {
	const errors = validate(c.body);

	if (errors.length > 0) {
		throw new C.Exception("Validation failed", C.Status.BAD_REQUEST, { errors });
	}

	return { valid: true };
});

Using the response getter

new C.Route("/handle", async (c) => {
	try {
		return await riskyOperation();
	} catch (err) {
		if (err instanceof C.Exception) {
			// this is already done in the Server.handleError
			return err.response;
		}
		throw err;
	}
});

Checking error status

new C.Middleware({
	variant: "inbound",
	useOn: "*",
	handler: (c) => {
		try {
			return c.next();
		} catch (err) {
			if (err instanceof C.Exception && err.isStatusOf(C.Status.UNAUTHORIZED)) {
				c.res.headers.set("X-Auth-Required", "true");
			}
			throw err;
		}
	},
});

Constructor Parameters

message

string

The error message. Available on error.message.

status

Status

HTTP status code for this error. Use C.Status enum for standard codes.

data (optional)

unknown

Additional data to include in the response. If a Res is passed, it will be modified with the status code and returned as-is in the res getter.

Properties

PropertyTypeDescription
messagestringError message (inherited from Error)
statusStatusHTTP status code
dataunknownOptional additional payload
responseResGetter to transform to Res, see below

response

get response(): Res

Converts the error to a Res:

// With plain data
const err = new C.Exception("Not found", C.Status.NOT_FOUND);
return err.response;
// → Res with body { error: true, message: "Not found" }

// With Res data
const err = new C.Exception("Failed", C.Status.BAD_REQUEST, new C.Res("custom"));
return err.response; // → The passed Res with status 400

Methods

isStatusOf

isStatusOf(status: Status): boolean

Checks if the error matches a specific HTTP status code.

const err = new C.Exception("Not found", C.Status.NOT_FOUND);
err.isStatusOf(C.Status.NOT_FOUND); // true
err.isStatusOf(C.Status.BAD_REQUEST); // false