mikemaccana
mikemaccana

Reputation: 123128

How can I ignore certain Errors? eslint no-ex-assign complains

I have some code that tries to do something. Sometimes that fails for a specific reason which I don't consider a failure. But I still want to catch real Errors.

This code works perfectly, but eslint complains:

try {
    doThing()
}   catch (err) {
    if ( err.message.includes('already exists') ) {
        err = null;
    }
    if ( err ) {
        throw new Error(`Oh no something really bad happened!`)
    }
}

I'm aware assigning err to null is destructive: that's why I am doing it, since I do not consider this a valid Error and want nothing more to do with it.

Is there a better way this should be handled? Obviously I could add a condition to the throw block, but that doesn't seem as explicit.

Can I jump out of the catch clock early, for example?

Upvotes: 1

Views: 171

Answers (1)

str
str

Reputation: 44969

Why don't you think, adding a condition to the throw block is explicit? Personally, I think this is much more readable:

try {
    doThing()
} catch (err) {
    const canExceptionBeIgnored = err.message.includes('already exists'); 
    if (!canExceptionBeIgnored) {
        throw new Error(`Oh no something really bad happened!`)
    }
}

Upvotes: 3

Related Questions