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.
El método toString()
devuelve una cadena que representa el objeto Error
especificado.
Sintaxis
e.toString()
Valor de retorno
Una cadena que representa el objeto Error
especificado.
Descripción
El objeto Error
redefine el método Object.prototype.toString()
heredado por todos los objetos. Su semántica es la siguiente (asumiendo que Object
y String
tienen sus valores 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;
};
Ejemplos
Usar toString()
js
var e = new Error("fatal error");
console.log(e.toString()); // 'Error: error fatal'
e.name = undefined;
console.log(e.toString()); // 'Error: error fatal'
e.name = "";
console.log(e.toString()); // 'error fatal'
e.message = undefined;
console.log(e.toString()); // ''
e.name = "hola";
console.log(e.toString()); // 'hola'
Especificaciones
Specification |
---|
ECMAScript® 2025 Language Specification # sec-error.prototype.tostring |
Compatibilidad con navegadores
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
toString |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.