Sasgorilla
Sasgorilla

Reputation: 3130

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?

Upvotes: 3

Views: 1083

Answers (2)

libik
libik

Reputation: 23029

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);
    }
})

Upvotes: 1

ulou
ulou

Reputation: 5853

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))

Upvotes: 1

Related Questions