更好的技术来扩展JavaScript中的错误?

时间:2016-11-08 04:59:55

标签: javascript error-handling

问:我的代码扩展Error()有时候因为缺少堆栈跟踪而没有完全成功(就像这里一样)。如何扩展Error()并始终获得堆栈跟踪?

我用过

我已经到达了此代码顶部的MyError():

"use strict"

/**
 * MyError (sync) - descends from Error
 * @param {string} inMsg - default null. Should be a string containing information about
 *   the error.
 * Note: technique for extending Error from
 *   https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
 *     (below heading "Custom Error Types"), as observed Mon Sep 19, 2016 and Tue Oct 18,
 *     2016 (the code example under that heading changed between those dates).
 *   https://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript,
 *     as observed Tue Oct 18, 2016. No mention of copyright restrictions noted.
 */
function MyError(inMsg = null) {
    this.name = "MyError"

    if (Object.prototype.toString.call(inMsg) === "[object String]" && inMsg.length > 0)
        { this.message = inMsg }
    else { this.message = "MyError was called without a message." }

    const lastPart = new Error().stack.match(/[^\s]+$/)
    this.stack = `${ this.name } at ${ lastPart }`
}
MyError.prototype = Object.create(Error.prototype)
MyError.prototype.name = "MyError"
MyError.prototype.message = ""
MyError.prototype.constructor = MyError
MyError.prototype.toString = function() { return `${ this.name }: ${ this.message }` }

/**
 * p and p1 - functions that demonstrate a behavior
 * @param { number } n - integer
 * @throw { LocError } - if n isn't an integer
 */
function p(n) {
    if (!Number.isInteger(n)) { throw new MyError(`n must be an integer   n=${ n }`) }
    // uses MyError()
}
function p1(n) {
    if (!Number.isInteger(n)) { throw new Error(`n must be an integer   n=${ n }`) }
    // uses Error()
}

if (true) {
    console.log(p(3))
    console.log(p("t"))
}
else {
    console.log(p1(3))
    console.log(p1("t"))
}

(该代码位于https://jsfiddle.net/BaldEagle/9vp0p3pw/,但我还没弄清楚如何在那里执行它。)

我的Windows 10是最新的。我正在使用Node v6.2.0。

代码底部有两个功能。一个调用Error();另一个调用MyError()。没有其他区别。

在它们下面是一个if语句,用于选择您观察的功能。将if语句设置为“true”(如图所示),您将看到My​​Error()的结果。我得到了

        if (!Number.isInteger(n)) { throw new MyError(`n must be an integer   n=${ n }`) }
                                    ^
 MyError at (node.js:160:18)

并且只有那个(没有堆栈跟踪)。

if语句设置为“false”,您将看到Error()的结果。我得到了

        if (!Number.isInteger(n)) { throw new Error(`n must be an integer   n=${ n }`) }
                                    ^

Error: n must be an integer   n=t
    at p1 (C:\path\file.js:38:36)

接着是8或10行首选堆栈跟踪。

问:我的代码扩展Error()有时候因为缺少堆栈跟踪而没有完全成功(就像这里一样)。如何扩展Error()并始终获得堆栈跟踪?

0 个答案:

没有答案