私は上記よりも強力な構文を好みます。エラータイプでの追加のメソッドは、あなたがかなりconsole.logまたは何か他のものを作成するのに役立ちます。
export class CustomError extends Error {
    /**
     * @param {string} message
     * @param {number} [code = 0]
     */
    constructor(message, code = 0) {
        super();
        /**
         * @type {string}
         * @readonly
         */
        this.message = message;
        /**
         * @type {number}
         * @readonly
         */
        this.code = code;
        /**
         * @type {string}
         * @readonly
         */
        this.name = this.constructor.name;
        /**
         * @type {string}
         * @readonly
         */
        this.stack = CustomError.createStack(this);
    }
    /**
     * @return {string}
     */
    toString() {
        return this.getPrettyMessage();
    }
    /**
     * @return {string}
     */
    getPrettyMessage() {
        return `${this.message} Code: ${this.code}.`;
    }
    /**
     * @param {CustomError} error
     * @return {string}
     * @private
     */
    static createStack(error) {
        return typeof Error.captureStackTrace === 'function'
            ? Error.captureStackTrace(error, error.constructor)
            : (new Error()).stack;
    }
}
このコードをテストするには、同様のコードを実行します。
try {
    throw new CustomError('Custom error was thrown!');
} catch (e) {
    const message = e.getPrettyMessage();
    console.warn(message);
}
CustomErrorタイプの拡張は大歓迎です。拡張タイプに特定の機能を追加したり、既存の機能をオーバーライドしたりすることができます。例えば。
export class RequestError extends CustomError {
    /**
     * @param {string} message
     * @param {string} requestUrl
     * @param {number} [code = 0]
     */
    constructor(message, requestUrl, code = 0) {
        super(message, code);
        /**
         * @type {string}
         * @readonly
         */
        this.requestUrl = requestUrl;
    }
    /**
     * @return {string}
     */
    getPrettyMessage() {
        const base = super.getPrettyMessage();
        return `${base} Request URL: ${this.requestUrl}.`;
    }
}