Home Manual Reference Source Test Repository

src/http_error.js

import {STATUS_CODES} from 'http';

/**
 * Represents an error caused by an improper request of the end-user.
 *
 * `HTTPError` can be differentiated via its `status` property value which keeps a standard HTTP status code (e.g. 404, 500).
 * Error handlers may use this status code to decide how to format the error page.
 */
export class HTTPError extends Error {

  /**
   * Initializes a new instance of the class.
   * @param {number} status The HTTP status code, such as 404, 500, etc.
   * @param {string} [message] The message that explains the reason for the error.
   * @param {boolean} [expose] Value indicating whether to expose the error message to the clients.
   */
  constructor(status, message = '', expose = true) {
    super(message);
    Error.captureStackTrace(this, HTTPError);

    /**
     * Value indicating whether to expose the error message to the clients.
     * @type {boolean}
     */
    this.expose = Boolean(expose);

    /**
     * The HTTP status code, such as 403, 404, 500, etc.
     * @type {number}
     */
    this.status = Number(status);

    /**
     * The user-friendly name of this error.
     * @type {string}
     */
    this.name = this.status in STATUS_CODES ? STATUS_CODES[this.status] : 'Error';
  }
}