Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!