ortense
9/23/2017 - 1:27 PM

A simple way to create elegant custom errors.

A simple way to create elegant custom errors with ES6 classes.

'use strict'

export class CustomError extends Error {
  constructor(message) {
    super(message)

    this.type = this.name = this.constructor.name

    Object.defineProperties(this, {
      type: { enumerable: true, writable: false },
      name: { enumerable: false, writable: false },
      message: { enumerable: true, writable: false },
    })
  }
}

export class PageNotFound extends CustomError {
  constructor(message) {
    super(message)

    this.statusCode = 404
    this.statusText = 'Page not found'

    Object.defineProperties(this, {
      statusCode: { enumerable: true, writable: false },
      statusText: { enumerable: true, writable: false },
    })
  }
}

const pnf = new PageNotFound('Can not get /foo')

/*
  { PageNotFound: Can not get /foo
    at Object.<anonymous> (/Users/ortense/projects/gists/custom-errors.js:27:13)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)
    at bootstrap_node.js:542:3
  message: 'Can not get /foo',
  type: 'PageNotFound',
  statusCode: 404,
  statusText: 'Page not found' }
*/