此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Error.prototype.toString()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
Error 实例的toString() 方法返回一个表示此错误的字符串。
In this article
语法
js
toString()参数
无。
返回值
一个表示指定Error 对象的字符串。
描述
Error 对象重写了所有对象继承的Object.prototype.toString() 方法。其语义如下:
js
Error.prototype.toString = function () { if ( this === null || (typeof this !== "object" && typeof this !== "function") ) { throw new TypeError(); } let name = this.name; name = name === undefined ? "Error" : `${name}`; let msg = this.message; msg = msg === undefined ? "" : `${msg}`; if (name === "") { return msg; } if (msg === "") { return name; } return `${name}: ${msg}`;};示例
>使用 toString()
js
const e1 = new Error("致命错误");console.log(e1.toString()); // "Error: 致命错误"const e2 = new Error("致命错误");e2.name = undefined;console.log(e2.toString()); // "Error: 致命错误"const e3 = new Error("致命错误");e3.name = "";console.log(e3.toString()); // "致命错误"const e4 = new Error("致命错误");e4.name = "";e4.message = undefined;console.log(e4.toString()); // ""const e5 = new Error("致命错误");e5.name = "你好";e5.message = undefined;console.log(e5.toString()); // "你好"规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-error.prototype.tostring> |