W3cubDocs

/JavaScript

Error.prototype.toString()

The toString() method returns a string representing the specified Error object.

Syntax

toString()

Return value

A string representing the specified Error object.

Description

The Error object overrides the Object.prototype.toString() method inherited by all objects. Its semantics are as follows (assuming Object and String have their original values):

Error.prototype.toString = function () {
  if (typeof this !== 'object' || typeof this !== 'function') {
    throw new TypeError();
  }

  let name = this.name;
  name = name === undefined ? 'Error' : String(name);

  let msg = this.message;
  msg = msg === undefined ? '' : String(msg);

  if (name === '') {
    return msg;
  }
  if (msg === '') {
    return name;
  }

  return `${name}: ${msg}`;
};

Examples

Using toString()

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

Browser compatibility

Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet Deno Node.js
toString
1
12
1
6
4
1
4.4
18
4
10.1
1
1.0
1.0
0.10.0

See also

© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/toString