How to throw error properly for a missing property? [duplicate]

北城余情 提交于 2019-12-24 12:56:25

问题


    if (win.NS && win.NS.molist && win.NS.molist.utility) {
        NS = win.NS;
        NS.molist.dom = true;
    } else {
        throw "dom requires utility module";
    }

For the snippet above, what is the proper way to throw an error, if win.NS.molist.utility does not exist?

Can I just throw up the text I want displayed to be shown in the debugger?

Perhaps, I should use one of the built in error types?

Maybe a new TypeError, I'm not sure as there are many global Errors objects.


回答1:


You can throw a completely custom Error.

function ModuleNotFoundError(message) {
  this.name = "ModuleNotFound";
  this.message = message || "dom does not have this module";
}
ModuleNotFoundError.prototype = new Error();
ModuleNotFoundError.prototype.constructor = ModuleNotFoundError;

throw new ModuleNotFoundError('win.NS.molist.utility');


来源:https://stackoverflow.com/questions/17845385/how-to-throw-error-properly-for-a-missing-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!