我正在尝试创建我自己的异常(exception)。 所以我可以根据 nodejs 服务器运行的环境格式化错误。抛出错误时,这是未定义的。
(function () {
'use strict';
var states = require('../states');
var env = states.config.env;
var _ = require('underscore');
/**
* This is a error that is going to be thrown on server errors.
* The application format the message for the specific environment
* @param error The error
*/
var unrecoverableError = function (error) {
this.name = 'unrecoverableError';
this.message = _.isEqual(env, 'production') ? 'There was a server error. Please contact server admin' : error.toString();
this.code = 500;
};
unrecoverableError.prototype = Object.create(Error.prototype);
unrecoverableError.prototype.constructor = unrecoverableError;
module.exports = unrecoverableError;
}());
我也使用 sequelize 作为 ORM。
organisation.findOne({
where: {
name: organisationName
}
})
.then(function (organisation) {
if (_.isEmpty(organisation)) {
throw new modelNotFoundException();
} else {
resolve(organisation);
}
})
.catch(function (error) {
if (error instanceof modelNotFoundException) {
reject(error);
} else {
throw new unrecoverableError(error);
}
})
.catch(function (error) {
reject(error);
});
然后在我的控制台中出现错误。
[类型错误:无法设置未定义的属性“名称”]
我不知道我做错了什么。它在浏览器中工作。 这是一个有效的 fiddle 示例。 https://jsfiddle.net/y3gk0hos/
提前致谢
最佳答案
错误的发生是因为 "use strict";
声明阻止了全局环境的“非法”访问。
如果调用函数 unrecoverableError
时没有使用 new
关键字,则 this
对象将指向全局环境。虽然在浏览器中允许,但 'use strict';
语句不允许这样做。
为了确保 unrecoverableError
方法实例化一个对象,您需要检查它是否在没有 new
关键字的情况下执行并强制正确使用:
var unrecoverableError = function (error) {
// check if called with 'new'
if (this instanceof unrecoverableError) {
this.name = 'unrecoverableError';
this.message = 'There was a server error. Please contact server admin';
this.code = 500;
}
else {
// method was not called with 'new'
return new unrecoverableError(error);
}
};
关于javascript - 自定义异常。这个未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36105921/