ortense
3/7/2017 - 1:28 PM

Custom Error with readonly properties and enumerable message for visibility on JSON.stringify

Custom Error with classes

const propertyDescriptor = { enumerable: true, writable: false }

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

    this.type = this.constructor.name
    Object.defineProperty(this, 'type', propertyDescriptor)
    Object.defineProperty(this, 'message', propertyDescriptor)
  }

  toJSON() {
    return JSON.stringify({
      type: this.type,
      message: this.message
    })
  }
}

// pode ser outro arquivo

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