このページはコミュニティーの尽力で英語から翻訳されました。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月.
toString() メソッドは、指定したError オブジェクトを表す文字列を返します。
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("fatal error");console.log(e1.toString()); // "Error: fatal error"const e2 = new Error("fatal error");e2.name = undefined;console.log(e2.toString()); // "Error: fatal error"const e3 = new Error("fatal error");e3.name = "";console.log(e3.toString()); // "fatal error"const e4 = new Error("fatal error");e4.name = "";e4.message = undefined;console.log(e4.toString()); // ""const e5 = new Error("fatal error");e5.name = "hello";e5.message = undefined;console.log(e5.toString()); // "hello"仕様書
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-error.prototype.tostring> |