Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda