Error.prototype.toString()

Error 实例的 toString() 方法返回表示此错误的字符串。

¥The toString() method of Error instances returns a string representing this error.

语法

¥Syntax

js
toString()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

表示指定 Error 对象的字符串。

¥A string representing the specified Error object.

描述

¥Description

Error 对象重写了所有对象继承的 Object.prototype.toString() 方法。其语义如下:

¥The Error object overrides the Object.prototype.toString() method inherited by all objects. Its semantics are as follows:

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}`;
};

示例

¥Examples

使用 toString()

¥Using 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 Language Specification
# sec-error.prototype.tostring

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看