0

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?

mikemaccana
  • 110,530
  • 99
  • 389
  • 494

1 Answers1

3

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!`)
    }
}
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
str
  • 42,689
  • 17
  • 109
  • 127
  • @mikemaccana Yes, you can use `return`, but only if you are in a function. – str Jun 26 '17 at 11:30
  • 1
    @mikemaccana If you don't `throw` or `return` inside the `catch`, the interpreter will exit the `catch` and proceed with any lines of code that comes after the try-catch block – Lennholm Jun 26 '17 at 11:37
  • @mikemaccana I know that you want to ignore the error. You can return within an [IIFE](https://stackoverflow.com/questions/6340874/a-javascript-function) or use a condition as I described in my answer. – str Jun 26 '17 at 12:58
  • @str Fair enough. I've tightened it to just the second answer, upvoted it and marked it as approved. – mikemaccana Jun 26 '17 at 18:41