How to correctly trap and read any errors generate

2019-08-17 19:26发布

问题:

This question already has an answer here:

  • Wait until all ES6 promises complete, even rejected promises 16 answers

I currently have a node.js/graphql micro service that uses Promise.all to call another micro service via apolloFetch. My Promise.all part seems to be working ok but I'm trying to have the error logging part working. I need to make sure that the Promise.all executes ALL THE PROMISES and not quit after it encounters the first error. Once it executes ALL THE PROMISES, I need to then populate an array meant just errors, which I then loop through and insert into a database using another function. I currently have the array and the catch set up, but when I intentionally generate an error, I don't see the array being populated.

Could someone take a gander if my code is indeed doing what I'm intending it to do?

     const ErrorsArray = [];
     Promise.all(promises.map(p => apolloFetch({p}))).then((result) =>                         

          {
                resolve();
                console.log("success!");
            }).catch((e) => {
                ErrorsArray.push( e );
            });
     if( ErrorsArray && ErrorsArray.length ){
        for(a=0;a<ErrorsArray.length;a++){
          funcLogErrors( ErrorsArray[a].errorCode,         
                         ErrorsArray[a].message );
         //Not sure if these are correct^^^^^^^^^
        }
      }

PS: Also, how do I simulate a mySQL database error without shutting my database down, so I can test this function to make sure all the database errors are being caught as well?

回答1:

Your ErrorsArray will always contain at most ONE error. This is because Promise.all either resolve all promises or fail (and reject) after the first error it encounters.

Simply put, there's no need for an array here since there's no scenario where you have multiple exceptions.

If you really want to have a "chain" like logic, you should look into Observables. You can convert your Promises into Observables using rxjs and more specifically with the catchError and switchMap operators