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 ãªãã¸ã§ã¯ãã表ãæååãè¿ãã¾ãã
æ§æ
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® 2027 Language Specification> # sec-error.prototype.tostring> |