Error.prototype.toString()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

La méthode toString() renvoie une représentation de l'objet Error sous la forme d'une chaine de caractères.

Syntaxe

js
e.toString();

Valeur de retour

Une chaîne de caractères représentant l'objet Error.

Description

L'objet Error surcharge la méthode Object.prototype.toString() héritée par tous les objets. Sa sémantique est la suivante (en partant du principe que Object et String ont leurs valeurs originales) :

js
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

js
var e = new Error("Erreur fatale");
console.log(e.toString()); // "Error: Erreur fatale"

e.name = undefined;
console.log(e.toString()); // "Error: Erreur fatale"

e.name = "";
console.log(e.toString()); // "Erreur fatale"

e.message = undefined;
console.log(e.toString()); // ""

e.name = "salut";
console.log(e.toString()); // "salut"

Spécifications

Specification
ECMAScript® 2025 Language Specification
# sec-error.prototype.tostring

Compatibilité des navigateurs

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
toString

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

Voir aussi