Socket
Book a DemoInstallSign in
Socket

@alessiofrittoli/exception

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@alessiofrittoli/exception

Handle errors with ease

latest
Source
npmnpm
Version
3.2.0
Version published
Maintainers
1
Created
Source

Exception 🚦

NPM Latest Version Coverage Status Socket Status NPM Monthly Downloads Dependencies

GitHub Sponsor

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 Contents

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

API Reference

ExceptionOptions Interface

The ExceptionOptions interface defines the optional parameters for the Exception class constructor.

Properties
PropertyTypeDefaultDescription
codeTCode-(Required) A numeric or custom code representing the error type.
namestringException(Optional) A string representing the error name.
statusnumber-(Optional) An HTTP status code associated with the error.

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
ParameterTypeDescription
messageTMessage(Required) The error message. Can be a string or a custom type.
optionsExceptionOptions(Required) An object containing the error options.
Example
import { Exception } from '@alessiofrittoli/exception'

try {
  throw new Exception( '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( '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 )
  }
}
/** Simulates JSON Exception returned by a server JSON Response. */
const error = (
  JSON.parse( JSON.stringify( new Exception( 'Exception with custom name.', {
    code: 0,
    name: 'AbortError',
  } ) ) )
)

console.log( Exception.isException( error ) ) // Outputs: true

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
ParameterTypeDescription
messageTMessage(Required) The error message. Can be a string or a custom type.
optionsAbortErrorOptions(Optional) 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( '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 CustomAbortCode
{
  CUSTOM_CODE = 'ERR:CUSTOM_ABORT_CODE',
}

try {
  const controller = new AbortController()
  const { signal } = controller

  button.addEventListener( 'click', () => {
    controller.abort(
      new AbortError( 'User cancelled the request.', { code: CustomAbortCode.CUSTOM_CODE } )
    )
  } )

  await fetch( ..., { signal } )
} catch ( error ) {

  if ( AbortError.isException( error ) ) {
    if ( AbortError.isAbortError( error, CustomAbortCode.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
  
}

ErrorCode enum

The ErrorCode enum is a utility that provides pre-defined constants for the most common error codes.
It is designed to simplify error handling and improve feedback quality returned to the user.

Constants Overview
ConstantValueDescription
UNKNOWNERR:UNKNOWNReturned when an unexpected error occured.
ABORTERR:ABORTReturned when user abort the request.
EMPTY_VALUEERR:EMPTYVALUEReturned when a required value is "falsy".
WRONG_VALUEERR:WRONGVALUEReturn when a required value is not the expected value.
EXPIREDERR:EXPIREDReturned when a requested has been performed too late.
TOO_EARLYERR:TOOEARLYReturned when a request has been performed too early.
TOO_MANYERR:TOOMANYCould be return in combination with a 429 Too Many Requests Response Status.
QUOTA_REACHEDERR:QUOTAREACHEDReturned when a specific quota has been reached.
NOT_FOUNDERR:NOTFOUNDReturned when a resource cannot be found.
OFFLINEERR:INTERNETDISCONNECTEDCould be used to throw errors when user is offline.
Extending the `enum` in your project

For obvious reasons the default ErrorCode provided by this library might be not enough to cover all the error cases in your project.

To fill this gap, you can "extend" the ErrorCode enum by doing so:

// myproject/src/error-code.ts
import { ErrorCode as Exception } from '@alessiofrittoli/exception/code'

/** Your project custom `ErrorCode`. */
export enum MyProjectErrorCode
{
  INVALID_SIGN = 'ERR:INVALIDSIGN',
}

const ErrorCode = { Exception, MyProjectErrorCode }
type ErrorCode = MergedEnumValue<typeof ErrorCode>

export default ErrorCode

⚠️ The Type MergedEnumValue<T> is globally delcared from @alessiofrittoli/type-utils so make sure to install it if needed.

Examples

Using the default ErrorCode to throw a new Exception
import { Exception } from '@alessiofrittoli/exception'
import { ErrorCode } from '@alessiofrittoli/exception/code'

throw new Exception( 'Password is a required field to log you in.', {
  code    : ErrorCode.EMPTY_VALUE,
  status  : 422,
} )
Using custom ErrorCode to throw a new Exception
import { Exception } from '@alessiofrittoli/exception'
import { ErrorCode } from '@/error-code' // previously created in `myproject/src/error-code.ts`

throw new Exception( 'Invalid signature.', {
  code    : ErrorCode.MyProjectErrorCode.INVALID_SIGN,
  status  : 403,
} )
Using ErrorCode to handle errors
import { ErrorCode } from '@/error-code' // previously created in `myproject/src/error-code.ts`

try {
  ...
} catch ( error ) {
  if ( Exception.isException<string, ErrorCode>( error ) ) {
    switch ( error.code ) { // `error.code` is now type of `ErrorCode` (custom).
      case ErrorCode.MyProjectErrorCode.INVALID_SIGN:
        console.log( 'The signature is not valid.' )
        break
      case ErrorCode.Exception.UNKNOWN:
      default:
        console.log( 'Unexpected error occured.' )
    }
  }
}

Development

Install depenendencies

npm install

or using pnpm

pnpm i

Build the source code

Run the following command to test and build code for distribution.

pnpm build

ESLint

warnings / errors check.

pnpm lint

Jest

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.

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.

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 security@alessiofrittoli.it to disclose any security vulnerabilities.

Made with ☕

avatar
Alessio Frittoli
https://alessiofrittoli.it | info@alessiofrittoli.it

Keywords

exceptions

FAQs

Package last updated on 02 May 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts