javascriptnode.jsecmascript-nextcustom-error-handlingunhandled-promise-rejection

Can ESLint help you prevent Unhandled-Promise-Rejections?


Does eslint have any ability to warn about places to prevent Unhandled-Promise-Rejections?

Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. - DEP0018

You know what, I kind of like how the engine currently handles Unhandled-Promise-Rejections; because when you have an Unhandled-Promise-Rejection, instead of your whole service crashing, the service keeps running and only the part that was dependent upon the erroneous promise instance fails to complete. Let's say the error was caused by some user input not anticipated by the programmer during validation. The very async function that had an exception lives on to serve other calls (ones that do not have that same unanticipated user input). Yes, there is trash in the program at this point, in the form of forever awaiting awaits that never resolve, but to me that's more robust than allowing the service to crash completely.

Anyway, I guess someone else has already decided that perfection is more important than robustness.

Therefore, it is time for me to make my code ugly and perfect by having .catch(()=>{}); appended shortly after all those awaits in my code that looked clean as MOP&GLOW previously.

Does ESlint offer anything to assist me in locating promises without catches? Are there any spec additions that are in the works, for addressing this ugliness and inconvenience?

Personally, I wish I could configure the engine to just terminate code that is down the promise chain from an UnhandledPromiseRejection. I certainly would like to address the issue more easily than adding all those .catch(()=>{}) to all my async function calls that are awaited.


Solution

  • ESLint itself does not have the functionality you are looking for, but there is a highly popular plugin called eslint-plugin-promise.

    Specifically, the catch-or-return rule does what you are asking for:

    Ensure that each time a then() is applied to a promise, a catch() is applied as well. Exceptions are made if you are returning that promise.

    Valid

    myPromise.then(doSomething).catch(errors)
    myPromise
      .then(doSomething)
      .then(doSomethingElse)
      .catch(errors)
    function doSomethingElse() {
      return myPromise.then(doSomething)
    }
    

    Invalid

    myPromise.then(doSomething)
    myPromise.then(doSomething, catchErrors) // catch() may be a little better
    function doSomethingElse() {
      return myPromise.then(doSomething)
    }