Error.prototype.toString() - JavaScript 编辑
The toString()
method returns a string representing the specified Error
object.
Syntax
e.toString()
Return value
A string representing the specified Error
object.
Description
The Error
object overrides the Object.prototype.toString()
method inherited by all objects. Its semantics are as follows (assuming Object
and String
have their original values):
Error.prototype.toString = function() {
'use strict';
var obj = Object(this);
if (obj !== this) {
throw new TypeError();
}
var name = this.name;
name = (name === undefined) ? 'Error' : String(name);
var msg = this.message;
msg = (msg === undefined) ? '' : String(msg);
if (name === '') {
return msg;
}
if (msg === '') {
return name;
}
return name + ': ' + msg;
};
Examples
Using toString()
var e1 = new Error('fatal error');
console.log(e1.toString()); // 'Error: fatal error'
var e2 = new Error('fatal error');
e2.name = undefined;
console.log(e2.toString()); // 'Error: fatal error'
var e3 = new Error('fatal error');
e3.name = '';
console.log(e3.toString()); // 'fatal error'
var e4 = new Error('fatal error');
e4.name = '';
e4.message = undefined;
console.log(e4.toString()); // ''
var e5 = new Error('fatal error');
e5.name = 'hello';
e5.message = undefined;
console.log(e5.toString()); // 'hello'
Specifications
Specification |
---|
ECMAScript (ECMA-262) The definition of 'Error.prototype.toString' in that specification. |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论