0

我使用 Node Js 12。我有以下代码和错误。我想从内部捕获重新抛出错误并在外部捕获它。如何修改我的代码以实现错误重新抛出?谢谢。

function test() {

  try {

    // Some other code before promise chain below that could cause exception

    return Promise.resolve()
      .then(() => {
        const e = new Error();
        e.message = 'testtest';
        e.statusCode = 404;
        throw e;
      })
      .catch(err => {
        console.log('==inner===', err);
        throw err;
      });
  
  
  
  } catch (err) {
    console.log('==outer===', err);
  }
}


test();

错误

jfan@ubuntu2004:~/Desktop/temp/d$ node index.js 
==inner=== Error: testtest
    at /home/jfan/Desktop/temp/d/index.js:17:19 {
  statusCode: 404
}
(node:34826) UnhandledPromiseRejectionWarning: Error: testtest
    at /home/jfan/Desktop/temp/d/index.js:17:19
(node:34826) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:34826) [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.
jfan@ubuntu2004:~/Desktop/temp/d$
4

1 回答 1

0

建议

// define an async function for the purpose of awating a promise inside the function
// optional useError parameter is used to trigger an error for testing purposes
// optional args parameter is for passing any additional parameters to this function for example

async function test(useError=false, args=[]) {
  try {

    // Some other code before promise chain below that could cause exception
    if(useError) {
        throw new Error(`Some error occured while processing ${args[0]}...`);
    }

    // await the promise and store the result in a variable
    const promisedData = await Promise.resolve(`Promise delivered with ${args[0] ? args[0] : 'nothing'}!`);

    // return the result (this will be a promise)
    return promisedData;
  } catch (err) {
    // catch error that occurs within try block
    console.log('==outer===', err);
  }
}

// a simple generic async function runner for example
async function genericAsyncFunctionRunner(asyncFunction, ...args) {
    let [useError, ...otherArgs] = args;
    useError = useError ? true : false;
    const result = await asyncFunction(useError, otherArgs);

    // Output the result in console for example
    console.log(result);
}

// run asyn function using the generic async function runner with/without arguments 
genericAsyncFunctionRunner(test); // Promise delivered with nothing!
genericAsyncFunctionRunner(test, false, 'gratitude'); // Promise delivered with gratitude!
genericAsyncFunctionRunner(test, true, 'gratitude'); // ==outer=== Error: Some error occured while processing gratitude...
于 2020-07-23T01:17:45.987 回答