tsentials/errors
Errors are values, not exceptions. AppError is a frozen plain object with a code, description, type, and optional metadata.
Installation
npm install tsentials
Import
import { DomainError, Err, ErrorMetadata, ErrorType } from 'tsentials/errors';
import type { AppError } from 'tsentials/errors';
Important: Import
Errfrom'tsentials/errors'— NOT from'tsentials/result'.
Creating Errors
All parameters have defaults — pass only what you need.
Err.failure('Order.Rejected', 'The order was rejected.')
Err.validation('Field.Required', 'Name is required.')
Err.notFound('User.NotFound', 'User does not exist.')
Err.unexpected('DB.ConnectionFailed', 'Cannot connect to database.')
Err.conflict('Email.AlreadyTaken', 'This email is already in use.')
Err.unauthorized('Auth.InvalidToken', 'Token is expired.')
Err.forbidden('Permissions.Denied', 'Insufficient permissions.')
// With metadata — must use ErrorMetadata.fromRecord(), NOT a plain object
Err.validation('Age.Invalid', 'Must be 18+', ErrorMetadata.fromRecord({ field: 'age', value: 15 }))
// Convert a caught exception to AppError
try {
JSON.parse(raw);
} catch (e) {
const err = Err.fromException(e); // ErrorType.Failure by default
const err2 = Err.fromException(e, ErrorType.Validation, 'Json.Invalid'); // override type and code
const err3 = Err.fromException(e, ErrorType.Unexpected, { code: 'Db.Down', description: 'Database is unreachable' }); // override description too
}
// Combine multiple AppErrors into an array
const errs: AppError[] = Err.combine(Err.validation('A', 'a'), Err.notFound('B', 'b'));
// Structural equality: code + description + type + metadata (nested maps and Err errors by value, cycle-safe)
Err.equals(errA, errB); // boolean
AppError Properties
const error: AppError = Err.notFound('User.NotFound', 'User not found.');
error.code // 'User.NotFound'
error.description // 'User not found.' — NOT .message
error.type // ErrorType.NotFound
error.metadata // ErrorMetadata | undefined (ReadonlyMap<string, unknown>)
Critical: The property is
.description, not.message. AppError intentionally avoids the native Error.messagefield.
Err Factory Reference
| Method | ErrorType | Default code |
|--------|-----------|--------------|
| Err.failure(code?, desc?, metadata?) | Failure | 'Failure' |
| Err.unexpected(code?, desc?, metadata?) | Unexpected | 'Unexpected' |
| Err.validation(code?, desc?, metadata?) | Validation | 'Validation' |
| Err.conflict(code?, desc?, metadata?) | Conflict | 'Conflict' |
| Err.notFound(code?, desc?, metadata?) | NotFound | 'NotFound' |
| Err.unauthorized(code?, desc?, metadata?) | Unauthorized | 'Unauthorized' |
| Err.forbidden(code?, desc?, metadata?) | Forbidden | 'Forbidden' |
| Err.fromException(error, type?, code? \| { code?, description? }, metadata?) | Failure (default) | error.constructor.name |
| Err.combine(...errors) | — | returns AppError[] |
| Err.equals(a, b) | — | returns boolean |
| Err.with(error, patch) | patch or original | frozen copy with code/description/type/metadata replaced |
| Err.toJSON(error) | n/a | returns AppErrorJson |
| Err.fromJSON(json) | from JSON | returns Result<AppError> |
Copying and JSON
Spreading an AppError ({ ...err, code }) gives an unfrozen object without toJSON. Use Err.with instead:
const wrapped = Err.with(err, { code: `Api.${err.code}` }); // frozen, keeps toJSON
const bare = Err.with(err, { metadata: undefined }); // drops metadata
JSON.stringify(err) writes { code, description, type, numericType, metadata? }. Err.fromJSON validates a parsed value and revives it:
const r = Err.fromJSON(JSON.parse(raw)); // Result<AppError>
if (!r.ok) r.errors[0].code; // 'AppError.InvalidJson', metadata.path names the bad field
It also reads the CSharpEssentials Error shape: keys in any case (Code or code), type as a name in any case or an ordinal (0 to 7), falling back to numericType, and metadata as an object, null or absent. Nested metadata records such as innerException stay plain objects, so an error from Err.fromException does not come back Err.equals to the original. Use Result.fromJSON from tsentials/result for a whole Result.
ErrorType Enum
import { ErrorType } from 'tsentials/errors';
ErrorType.Failure // general failure
ErrorType.Validation // 400-class, user input errors
ErrorType.NotFound // 404
ErrorType.Conflict // 409
ErrorType.Unauthorized // 401
ErrorType.Forbidden // 403
ErrorType.Unexpected // 500, programming/infrastructure errors
ErrorType.Unknown // unclassified
Note: There is no
ErrorType.Custom. Use the typed factory that matches your semantic intent.
ErrorMetadata
ErrorMetadata is ReadonlyMap<string, unknown> — NOT a plain object. Use the namespace helpers to create and manipulate it.
import { ErrorMetadata } from 'tsentials/errors';
// Create
ErrorMetadata.empty() // empty map
ErrorMetadata.fromRecord({ field: 'email', value: 'bad@' }) // from plain object
ErrorMetadata.fromException(caughtError) // extracts exceptionType, exceptionMessage, exceptionStackTrace (+ nested innerException when `cause` is an Error)
ErrorMetadata.withStackTrace() // current call stack under `stackTrace`
// Combine (additional overrides base on key conflict)
ErrorMetadata.combine(base, additional?)
// Convert back to plain object
ErrorMetadata.toRecord(metadata) // Record<string, unknown>
// Full example: error with metadata
const meta = ErrorMetadata.fromRecord({ field: 'age', provided: 15, minimum: 18 });
const err = Err.validation('User.InvalidAge', 'Must be 18 or older.', meta);
// Read metadata
if (err.metadata) {
const record = ErrorMetadata.toRecord(err.metadata);
console.log(record.field); // 'age'
}
Domain-Specific Error Hierarchies
Group errors in plain objects per domain for IDE autocomplete and type-safe codes:
import { Err } from 'tsentials/errors';
import type { AppError } from 'tsentials/errors';
const UserErrors = {
notFound: (id: string): AppError =>
Err.notFound('User.NotFound', `User '${id}' was not found.`),
alreadyExists: Err.conflict('User.AlreadyExists', 'A user with that email already exists.'),
invalidAge: (age: number): AppError =>
Err.validation('User.InvalidAge', `Age ${age} is invalid; must be 18 or older.`),
unauthorized: Err.unauthorized('User.Unauthorized', 'You are not authorized.'),
} as const;
// Usage with Result<T>
function findUser(id: string): Result<User> {
const user = repo.find(id);
return user ? Result.success(user) : Result.failure(UserErrors.notFound(id));
}
DomainError: throwing typed errors
When code has to throw (a constructor, a callback, a deep call chain), throw a DomainError instead of a plain Error. It is an Error subclass that carries one or more AppError values.
throw new DomainError(Err.conflict('Order.Shipped', 'Order is already shipped'));
throw new DomainError([errA, errB], 'optional message');
const e = new DomainError(errA);
e.errors; // readonly AppError[] (a frozen copy)
e.error; // first error
e.message; // first error's description unless a message is given
Result.try, Result.tryAsync, Result.tryCatch, Result.tryCatchAsync and the mediator's exceptionHandlingBehavior return the carried errors as-is instead of Err.fromException(e), even when an onError mapper or fixed error is given. A DomainError with no errors is converted like any other exception. Abort errors still propagate. ResultUnwrapError (thrown by Result.unwrap) is a DomainError, so Result.try(() => Result.unwrap(r)) keeps r's errors.
Using with Result\<T\>
import { Result } from 'tsentials/result';
import { Err, ErrorType } from 'tsentials/errors';
function divide(a: number, b: number): Result<number> {
if (b === 0) return Result.failure(Err.validation('Math.DivideByZero', 'Cannot divide by zero.'));
return Result.success(a / b);
}
// Accessing errors from a failed Result
const result = divide(10, 0);
if (!result.ok) {
result.errors.forEach(e => console.log(`[${e.type}] ${e.code}: ${e.description}`));
}
// Wrapping a try/catch with fromException
async function fetchData(url: string): Promise<Result<Data>> {
try {
const res = await fetch(url);
return Result.success(await res.json() as Data);
} catch (e) {
return Result.failure(Err.fromException(e, ErrorType.Unexpected, 'Http.FetchFailed'));
}
}
Best Practices
- Group errors in const objects per domain — rules read like domain language
- Use
.description— the field isdescription, notmessage - Import
Errfrom'tsentials/errors', not'tsentials/result' - Use
ErrorMetadata.fromRecord({...})to attach metadata — never pass a plain object directly - Prefer factory functions (parameterized) over static values when the message includes runtime data
- Use
Err.unexpected()for programming/infrastructure errors andErr.validation()for user input errors - Use
Err.failure()for domain-level failures that are expected outcomes (not bugs, not user input) - Use
Err.fromException()to convert caught exceptions into typedAppErrorvalues - Throw
DomainErrorrather than a plainErrorwhen you must throw a typed error