Exception 🚦
Handle errors with ease
This documentation describes the Exception class, which provides a structured way to handle errors in TypeScript. It includes custom properties such as code, name, and status for more detailed error reporting and debugging.
Table of Content
Overview
The Exception class extends the native JavaScript Error object, adding customizable fields to improve error classification and handling. It also includes a static utility method to check if an object is an instance of the Exception class.
Getting started
Run the following command to start using @alessiofrittoli/exception in your projects:
npm i @alessiofrittoli/exception
or using pnpm
pnpm i @alessiofrittoli/exception
Development
Run the following to start development
nvm use
pnpm i
Local development
Run the following
pnpm dev
This will generate unminified output code, sourcemaps and will enable source file watcher.
Production build
Run the following to create a local production build
pnpm build
This will generate minified output code without sourcemaps.
Unit tests
Run all the defined test suites by running the following:
# Run tests and watch file changes.
pnpm test:watch
# Run tests in a CI environment.
pnpm test:ci
Run tests with coverage
An HTTP server is then started to serve coverage files from ./coverage folder.
⚠️ You may see a blank page the first time you run this command. Simply refresh the browser to see the updates.
pnpm test:coverage:serve
Contributing
Contributions are truly welcome!
Please refer to the Contributing Doc for more information on how to start contributing to this project.
Help keep this project up to date with GitHub Sponsor.
Security
If you believe you have found a security vulnerability, we encourage you to responsibly disclose this and NOT open a public issue. We will investigate all legitimate reports. Email [email protected] to disclose any security vulnerabilities.
API Reference
ExceptionOptions Interface
The ExceptionOptions interface defines the optional parameters for the Exception class constructor.
Properties
| Property | Type | Default | Description |
|---|---|---|---|
name | string | ExceptionName.Exception | (Optional) The error interface name. |
message | string | "Unknown error." | (Optional) The error message containing technical informations about the error. |
title | string | - | (Optional) The error title. |
description | string | - | (Optional) The error description. |
code | T | - | (Required) The error code associated with the Exception. |
isCritical | boolean | false | (Optional) Indicates whether the error is a critical error. |
status | number | - | (Optional) The HTTP status code associated with the Exception. |
cause | unknown | - | (Optional) The error cause. |
Exception Class
The Exception class extends the Error object and implements the ExceptionOptions interface.
Constructor
The constructor initializes an Exception instance with a custom message and options.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | ExceptionOptions | (Required) An object containing the error options. |
Example
import { Exception } from '@alessiofrittoli/exception'
try {
throw new Exception({
message: 'Resource not found'
code: 'ERR:NOTFOUND',
status: 404,
})
} catch (error) {
console.error(error)
}
Static Methods
isException
A utility method to check if an object is an instance of the Exception class.
It supports also a JSON representation of the Exception class (commonly returned by server responses).
Example
try {
throw new Exception({ message: 'Something went wrong', code: 'ERR:UNKNOWN' })
} catch (error) {
if (Exception.isException(error)) {
// we can safely access `Exception` properties
console.error(`Error [${error.code}]: ${error.message}`)
} else {
console.error(error)
}
}
import { ExceptionName } from '@alessiofrittoli/exception'
/** Simulates JSON Exception returned by a server JSON Response. */
const error = JSON.parse(
JSON.stringify(
new Exception({
name: ExceptionName.AbortError,
message: 'Exception with custom name.',
code: 0,
}),
),
)
console.log(Exception.isException(error)) // Outputs: true
console.log(new Exception(error)) // Outputs: [Exception]
AbortError Class
The AbortError class extends the Exception Class and offers a preset configuration for easier usage.
Constructor
The constructor initializes an AbortError instance with a custom message and options.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | AbortErrorOptions | An object containing the error options. |
It extends the ExceptionOptions Interface and omit the name property. | ||
The code defaults to ErrorCode.ABORT but can be optionally customized. |
AbortError Usage Scenarios
Precise Abort Errors Handling
import { AbortError } from '@alessiofrittoli/exception/abort'
try {
const controller = new AbortController()
const { signal } = controller
button.addEventListener('click', () => {
controller.abort(new AbortError({ message: 'User cancelled the request.' }))
})
await fetch(..., { signal })
} catch (error) {
if (AbortError.isException(error)) {
if (AbortError.isAbortError(error)) {
// handle abort error
console.log(error.code) // `error.code` is type of `ErrorCode.ABORT`.
return
}
// handle other Exception errors
return
}
// handle other unknown errors
}
Using custom Abort Error codes
import { AbortError } from '@alessiofrittoli/exception/abort'
enum ApplicationErrorCode {
CUSTOM_CODE = 'ERR:CUSTOM_ABORT_CODE',
}
try {
const controller = new AbortController()
const { signal } = controller
button.addEventListener('click', () => {
controller.abort(
new AbortError({
message: 'User cancelled the request.',
code: ApplicationErrorCode.CUSTOM_CODE,
}),
)
})
await fetch('', { signal })
} catch (error) {
if (AbortError.isException<ApplicationErrorCode>(error)) {
if (AbortError.isAbortError(error, ApplicationErrorCode.CUSTOM_CODE)) {
// handle abort error
console.log(error.code) // `error.code` is type of `CustomAbortCode.CUSTOM_CODE`.
return
}
// handle other Exception errors
return
}
// handle other unknown errors
}
Made with ☕
|
|
|