Options
All
  • Public
  • Public/Protected
  • All
Menu

Node Exceptions

NPM Version Build Status Appveyor Coveralls

Throwing errors in Javascript does not give much information about the error type as it is really hard to throw custom exceptions. Node Exceptions is a tiny wrapper which will let you extend the Error class and throw custom errors.

Why custom errors

Errors are thrown anywhere inside the code and handling them properly is required. For example you have an HTTP application, which can throw multiple errors and in order to handle those errors gracefully, you need to know the error types or their names.

switch (err.name) {
  case 'HttpException':
    // do something
  case 'RunTimeException':
    // do something else
}

Install

npm i --save node-exceptions

Creating custom errors

const NE = require('node-exceptions')

class MyCustomError extends NE.LogicalException {}

try {
  throw new MyCustomError('Something bad happened')
} catch (e) {
  console.log(e.status) // equals 500
  console.log(e.name) // equals MyCustomError
  console.log(e.message) // Something bad happened
  console.log(e.stack) // Error stack with correct reference to filepath and linenum
  console.log(e.toString()) // MyCustomError: Something bad happened
}

Custom error status

It is also possible to have a custom error status when throwing exceptions.

const NE = require('node-exceptions')

class HttpException extends NE.LogicalException {}

try {
  throw new HttpException('Page not found', 404)
} catch (e) {
  console.log(e.status) // equals 404
}

Also NE comes with some commonly required Exception classes which includes.

DomainException

When something excepted has failed. For example image upload mismatch extension.

throw new NE.DomainException()

InvalidArgumentException

Method arguments are invalid or incomplete.

throw new NE.InvalidArgumentException()

RangeException

Error caused due to arithmetic operations.

throw new NE.RangeException()

RuntimeException

An error occured after all required checks.

throw new NE.RuntimeException()

HttpException

Http specific errors.

throw new NE.HttpException()

Index

External modules

Legend

  • Module
  • Object literal
  • Variable
  • Function
  • Function with type parameter
  • Index signature
  • Type alias
  • Enumeration
  • Enumeration member
  • Property
  • Method
  • Interface
  • Interface with type parameter
  • Constructor
  • Property
  • Method
  • Index signature
  • Class
  • Class with type parameter
  • Constructor
  • Property
  • Method
  • Accessor
  • Index signature
  • Inherited constructor
  • Inherited property
  • Inherited method
  • Inherited accessor
  • Protected property
  • Protected method
  • Protected accessor
  • Private property
  • Private method
  • Private accessor
  • Static property
  • Static method

Generated using TypeDoc