Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

create-error-types

Package Overview
Dependencies
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

create-error-types

Create multiple error types

  • 1.0.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
0
decreased by-100%
Maintainers
1
Weekly downloads
 
Created
Source

Codecov TypeScript Node Twitter Medium

Create multiple error types.

Features

Example

Create the error types and handler.

// `error.js`
import createErrorTypes from 'create-error-types'

export const {
  errorHandler,
  // Those error types are examples.
  // Any name ending with "Error" can be specified.
  InputError,
  AuthError,
  DatabaseError,
} = createErrorTypes()

Wrap the main function with the error handler.

import { errorHandler } from './error.js'

export const main = async function (filePath) {
  try {
    return await readContents(filePath)
  } catch (error) {
    throw errorHandler(error)
  }
}

Throw/re-throw errors.

import { InputError } from './error.js'

const readContents = async function (filePath) {
  try {
    return await readFile(filePath)
  } catch (cause) {
    throw new InputError(`Could not read ${filePath}`, { cause })
  }
}

Install

npm install create-error-types

This package is an ES module and must be loaded using an import or import() statement, not require().

API

createErrorTypes(options?)

options object
Return value: object

Creates the error types and handler.

Return value

Any error type

Type: ErrorType

Any error type can be retrieved from the return value. The name must end with Error. For example: InputError, AuthError, etc.

errorHandler

Type: (anyException) => Error

Error handler that should wrap each main function.

Options

bugsUrl

Type: string | URL

URL where users should report internal errors/bugs.

onCreate

Type: (error, parameters) => void

Called on any new ErrorType('message', parameters). Can be used to customize error parameters or set error type properties. By default, any parameters are set as error properties.

Usage

Setup

Create error types and handler

✨ Retrieving the error types automatically creates them. ✨

// error.js
import createErrorTypes from 'create-error-types'

export const {
  errorHandler,
  // Those error types are examples.
  // Any name ending with "Error" can be specified.
  InputError,
  AuthError,
  DatabaseError,
} = createErrorTypes()

Error handler

Each main function should be wrapped with the errorHandler().

import { errorHandler } from './error.js'

export const main = async function (filePath) {
  try {
    return await readContents(filePath)
  } catch (error) {
    // `errorHandler()` returns `error`, so `throw` must be used
    throw errorHandler(error)
  }
}

Throw errors

import { InputError } from './error.js'

const validateFilePath = function (filePath) {
  if (filePath === '') {
    throw new InputError('Missing file path.')
  }
}

Error types

Test error type

Once errorHandler() has been applied, the error type can be checked by its name. Libraries should document their possible error names, but do not need to export their error types.

if (error.name === 'InputError') {
  // ...
} else if (error.name === 'InternalError') {
  // ...
}

Set error type

error.cause can be used to override the type of an inner error.

try {
  throw new AuthError('Could not authenticate.')
} catch (cause) {
  throw new InputError('Could not read the file.', { cause })
  // Now an InputError
}

Internal errors

Internal errors/bugs can be distinguished from user errors by:

The errorHandler() assigns the InternalError type to any error with an unknown type.

const getUserId = function (user) {
  return user.id
}

getUserId(null) // InternalError: Cannot read properties of null (reading 'id')

Bug reports

If the bugsUrl option is used,

createErrorTypes({ bugsUrl: 'https://github.com/my-name/my-project/issues' })

any internal error will include the following message.

Please report this bug at: https://github.com/my-name/my-project/issues

Error properties

Set error properties

Unless the onCreate() option is defined, any parameter is set as an error property.

const error = new InputError('Could not read the file.', { filePath: '/path' })
console.log(error.filePath) // '/path'

Customize error parameters

The onCreate() option can be used to validate and transform error parameters.

createErrorTypes({
  onCreate(error, parameters) {
    const { filePath } = parameters

    if (typeof filePath !== 'string') {
      throw new Error('filePath must be a string.')
    }

    const hasFilePath = filePath !== undefined
    Object.assign(error, { filePath, hasFilePath })
  },
})
const error = new InputError('Could not read the file.', {
  filePath: '/path',
  unknownParam: true,
})
console.log(error.filePath) // '/path'
console.log(error.hasFilePath) // true
console.log(error.unknownParam) // undefined

Type-specific logic

The onCreate() option can trigger error type-specific logic.

createErrorTypes({
  onCreate(error, parameters) {
    onCreateError[error.name](error, parameters)
  },
})

const onCreateError = {
  InputError(error, parameters) {
    // ...
  },
  AuthError(error, parameters) {
    // ...
  },
  // ...
}

Error type properties

The onCreate() option can be used to set properties on all instances of a given error type.

createErrorTypes({
  onCreate(error, parameters) {
    Object.assign(error, parameters, ERROR_PROPS[error.name])
  },
})

const ERROR_PROPS = {
  InputError: { isUser: true },
  AuthError: { isUser: true },
  DatabaseError: { isUser: false },
}
const error = new InputError('Could not read the file.')
console.log(error.isUser) // true

Support

For any question, don't hesitate to submit an issue on GitHub.

Everyone is welcome regardless of personal background. We enforce a Code of conduct in order to promote a positive and inclusive environment.

Contributing

This project was made with ❤️. The simplest way to give back is by starring and sharing it online.

If the documentation is unclear or has a typo, please click on the page's Edit button (pencil icon) and suggest a correction.

If you would like to help us fix a bug or add a new feature, please check our guidelines. Pull requests are welcome!

Keywords

FAQs

Package last updated on 17 Aug 2022

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc