Chained promises not passing on rejection

前端 未结 3 2017
挽巷
挽巷 2020-11-22 02:18

I am have a problem understanding why rejections are not passed on through a promise chain and I am hoping someone will be able to help me understand why. To me, attaching f

3条回答
  •  粉色の甜心
    2020-11-22 02:47

    Use can wrap the errors at each level of the Promise. I chained the errors in TraceError:

    class TraceError extends Error {
      constructor(message, ...causes) {
        super(message);
    
        const stack = Object.getOwnPropertyDescriptor(this, 'stack');
    
        Object.defineProperty(this, 'stack', {
          get: () => {
            const stacktrace = stack.get.call(this);
            let causeStacktrace = '';
    
            for (const cause of causes) {
              if (cause.sourceStack) { // trigger lookup
                causeStacktrace += `\n${cause.sourceStack}`;
              } else if (cause instanceof Error) {
                causeStacktrace += `\n${cause.stack}`;
              } else {
                try {
                  const json = JSON.stringify(cause, null, 2);
                  causeStacktrace += `\n${json.split('\n').join('\n    ')}`;
                } catch (e) {
                  causeStacktrace += `\n${cause}`;
                  // ignore
                }
              }
            }
    
            causeStacktrace = causeStacktrace.split('\n').join('\n    ');
    
            return stacktrace + causeStacktrace;
          }
        });
    
        // access first error
        Object.defineProperty(this, 'cause', {value: () => causes[0], enumerable: false, writable: false});
    
        // untested; access cause stack with error.causes()
        Object.defineProperty(this, 'causes', {value: () => causes, enumerable: false, writable: false});
      }
    }
    

    Usage

    throw new TraceError('Could not set status', srcError, ...otherErrors);
    

    Output

    Functions

    TraceError#cause - first error
    TraceError#causes - list of chained errors
    

提交回复
热议问题