在已返回的承诺中处理异常

时间:2019-02-12 00:03:20

标签: javascript node.js promise

我知道这不是最漂亮的代码,但是由于遗留问题,我需要坚持使用此工作流程。

问题是我无法冒起可能在返回的诺言的心脏中发生的任何异常。

该代码设计为rejectresolve都返回有效数据。因此,如果将const CONDITION更改为0.4,我们将被拒绝。如果const CONDITION的值保持在0.6,我们将获得分辨率。到目前为止有效。

但是,在我们遇到结构故障的情况下,例如在下面的示例中,我们尝试将错误的变量名传递给拒绝:

let reasoxxxx = '__FAILED__';
reject({error: reason, data: output});

我无法调用throw来使错误冒泡。因此,我收到了通常的丑陋消息,并且无法冒出适当的例外情况:

Exchange request was rejected due to error(s).
(node:224) UnhandledPromiseRejectionWarning: ReferenceError: reason is not defined
(node:224) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:224) [DEP0018] DeprecationWarning: 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.

有什么想法吗?删除的代码应该可以工作。

function fakeFetch() {
  // Promisify the request.
  return new Promise((resolve, reject) => {
    // Emulate an asynchroneous fetch.
    setTimeout(() => {
      let result = 0.4; // Change to 0.4 to trigger a failed fetch.
      if (result < 0.5) {;
        reject('__FAIL__');
      } else {
        resolve({name: 'apple', price: '1234.12', time: 1549926859970});
      }
    }, 2000);
  });
}

async function sendExchangeRequest(id, pair, symbols, callback)
{
  let err, result
  await fakeFetch().then((output) => { result = output }).catch((error) => {err = error})
  if(err){
    result = 'None'
  }else{
    err = 'None'
  }
  callback(err, result)
}

async function fetchExchangeData(id, pair, symbols) {
    // Promisify the request.
    try {
        return new Promise((resolve, reject) => {
            try {
                // Send the request.
                sendExchangeRequest(id, pair, symbols, ((err, output) => {
                    try{
                        if(err){
                            // Soft Failure
                            console.log('Exchange request was rejected due to error(s).');
                            reject({error: err, data: output});
                        }else{
                            // Success
                            console.log('Exchange request was successful.');
                            resolve({error: err, data: output});
                        }
                    } catch(error) {
                        throw error;
                    }
                }));
            } catch(error) {
                console.log('---\n', error, '\n---');
                throw error;
            }
        });
    } catch(error) {
        // Bubble up the error?
        console.log('+++\n', error, '\n+++');
        throw error;
    }
}

(async () => {
  await fetchExchangeData('myid', 'MYPAIR', 'mySymbol')
  .then((result) => console.log(result))
  .catch((failure) => console.log(failure))
})();

---编辑(01)---

我已经更新了示例,其中包括一个伪造的API调用。我希望这使我的问题更加清楚。

1 个答案:

答案 0 :(得分:0)

我认为您不了解异步功能的概念。您在try/catch中的第一个fetchExchangeData实际上什么也不做,也没有异步。最初的承诺中的try / catch也几乎没有用,因为我敢肯定sendExchangeRequest的大多数/所有问题都将由错误处理程序函数(err)处理。至于try / catch块,您不应在Promise中抛出错误,而应拒绝错误(这将使错误冒泡)。如果您使用的是异步功能,请仅尝试/捕获,而不使用回调。

function fetchExchangeData(id, pair, symbols) {
    // Promisify the request.
    return new Promise((resolve, reject) => {
        try {
            // Send the request.
            sendExchangeRequest(id, pair, symbols, ((err, output) => {
                try{
                    if(err){
                        // Soft Failure
                        console.log('Exchange request was rejected due to error(s).');
                        let reason = '__FAILED__';
                        reject({error: reason, data: output});
                    }else{
                        // Success
                        console.log('Exchange request was successful.');
                        resolve({error: '__NONE__', data: output});
                    }
                } catch(error) {
                    reject(error);
                }
            }));
        } catch(error) {
            console.log('---\n', error, '\n---');
            reject(error);
        }
    });
}