Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
In Javascript, how can I throw an error that prints an object to the console?

The console.error() (or console.log()) statement has some nice features like variable-length argument lists that print out objects (and arrays):

const spaghettio = {sauce: 'arrabiata', cheese: 'gorgonzola'}
console.log(`Uh oh,`, spaghettio)

The object is printed out in a way I can expand the keys, which is very handy for large objects:

object formatted by console.log()

But if I want to throw a real error, I don't have those options. So I usually end up doing this:

console.error(`Uh oh`, spaghettio)
throw new Error(`Uh oh: ${spaghettio}`)

The Error version generally does a crappy job of formatting the objects and arrays: Uh oh: [object Object]. I can do

throw new Error(`Uh oh: ${JSON.stringify(spaghettio)}`)

But no matter how I slice it it's not as nice as what console.error does.

Is there a better way to avoid repeating myself here while still printing out objects to the console?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Combining console.error with throw new Error is probably shortest way to achieve what you want (please notice that you won't be able to expand object in StackOverflow console, it will be fully printed here):

const spaghettio = {sauce: 'arrabiata', cheese: 'gorgonzola'}
throw new Error(console.error('Uh oh:', spaghettio))

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can create your own errors and then create custom handling, which can include i.e. objects:

class MyError extends Error {
    constructor(message, obj) {
        super(message);
        this.obj = obj;
    }
}

async function x() {
    throw new MyError('ab', { that: 'is', much: { really: 'weird' } });
}

x().catch(err => {
    if (err instanceof MyError) {
        console.error(err.message);
        console.error(err.obj);
    }
})

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda