Javascriptのカスタムエラーの作り方

function foo() { bar(); }
function bar() { baz(); }
function baz() { throw new Error('X'); }

(function main() {
    try {
        foo();
    } catch (error) {
        console.log(error.stack);
    }
})();


Error: X
    at baz (http://localhost/CustomError.html:8:24)
    at bar (http://localhost/CustomError.html:7:18)
    at foo (http://localhost/CustomError.html:6:18)
    at main (http://localhost/CustomError.html:12:9)
    at http://localhost/CustomError.html:16:3
var createError = (function () {
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    return function createError(name, message, properties) {
        var e = new Error(message);
        e.name = name;
        if (properties)
            for (var key in properties)
                if (hasOwnProperty.call(properties, key))
                    e[key] = properties[key];
        try {
            throw e; // for IE
        } catch (e) {
            return e;
        }
    };
})();

var timeoutError = createError('TimeoutError', 'session timeout');
var fetchError = createError('FetchError', '404 Not Found', { statusCode: 404 });