-
Notifications
You must be signed in to change notification settings - Fork 22.4k
/
index.md
90 lines (66 loc) · 1.81 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
---
title: Error.prototype.toString()
slug: Web/JavaScript/Reference/Global_Objects/Error/toString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Error.toString
---
{{JSRef}}
The **`toString()`** method of {{jsxref("Error")}} instances returns a string representing this error.
## Syntax
```js-nolint
toString()
```
### Parameters
None.
### Return value
A string representing the specified {{jsxref("Error")}} object.
## Description
The {{jsxref("Error")}} object overrides the {{jsxref("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
### 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"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Error.prototype.toString` with many bug fixes in `core-js`](https://github.com/zloirock/core-js#ecmascript-error)