Error.prototype.toString()

Resum

El m猫tode toString() retorna un string que representa l'error especificat per l'objecte Error.

Sintaxi

e.toString()

Descripci贸

L'objecte Error sobreescriu el m猫tode Object.prototype.toString() (en-US) heretat per tots els objectes. La seva sem脿ntica 茅s la seg眉ent (suposant que Object i String tenen els seus valors originals):

Error.prototype.toString = function() {
  'use strict';

  var obj = Object(this);
  if (obj !== this) {
    throw new TypeError();
  }

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

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

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

  return name + ': ' + msg;
};

Exemples

var e = new Error('fatal error');
print(e.toString()); // 'Error: fatal error'

e.name = undefined;
print(e.toString()); // 'Error: fatal error'

e.name = '';
print(e.toString()); // 'fatal error'

e.message = undefined;
print(e.toString()); // 'Error'

e.name = 'hello';
print(e.toString()); // 'hello'

Especificacions

Especificaci贸 Estat Comentaris
ECMAScript 1a Edici贸. Standard Definici贸 inicial. Implementat a JavaScript 1.1.
ECMAScript 5.1 (ECMA-262)
The definition of 'Error.prototype.toString' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Error.prototype.toString' in that specification.
Standard  

Compatibilitat amb navegadors

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help! (en-US)
Caracter铆stica Chrome Firefox (Gecko) Internet Explorer Opera Safari
Suport b脿sic (Yes) (Yes) (Yes) (Yes) (Yes)
Caracter铆stica Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Suport b脿sic (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

Vegeu tamb茅