[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Error/toString [Back]  [Original]

Error.prototype.toString() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Error.prototype.toString()

20157

Error toString()

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()); // ""

ECMAScript 2027 LanguageSpecification
# sec-error.prototype.tostring


Web Proxy Viewer  |  New URL  |  Original Page