简体   繁体   English

尝试/捕获未捕获快速异步函数中的所有错误?

[英]Try/catch not catching all errors in express async functions?

I have the following code.我有以下代码。

However, it's not catching all errors and I am still getting "throw er; // Unhandled 'error' event".但是,它并没有捕获所有错误,我仍然收到“throw er; // Unhandled 'error' event”。

Why is this?为什么是这样?

app.post('/api/properties/zip/:zip/bedrooms/:bedrooms', async (req, res, next) => {
  try {
    const file = await apiCall(req.params.zip, req.params.bedrooms);
    const records = await parse(file);
    const seq = await sequelize();
    const result = await dbImport(seq, records);
    return await res.status(200).json(`${result.length} properties successfully imported to the database`);
  } catch (err) {
    return next(err);
  }
});

// Middleware error handling
app.use((err, req, res, next) => {
  console.error(err.message);
  if (!err.statusCode) err.statusCode = 500;
  return res.status(err.statusCode).json(err.message);
});

For example, it didn't catch the error in the parse() function, until I added a specific error handler.例如,在我添加特定的错误处理程序之前,它没有捕获 parse() function 中的错误。 Shouldn't my try/catch catch this error even without adding this?即使不添加这个,我的 try/catch 不应该捕获这个错误吗?

const fs = require('fs');

const parse = filename => new Promise(((resolve, reject) => {
  // Converts a line from the file, parses it to JSON, and stores it an array
  const func = (data, records) => {
    const json = JSON.parse(data);
    records.push(json);
  };

  // Read in each line of the file and pass that line to func
  const readLines = (input) => {
    const records = [];
    let remaining = '';


    // ******** HAD TO ADD THIS *********
    input.on('error', (err) => {
      reject(err);
    });


    input.on('data', (data) => {
      remaining += data;
      let index = remaining.indexOf('\n');
      let last = 0;
      while (index > -1) {
        const line = remaining.substring(last, index);
        last = index + 1;
        func(line, records);
        index = remaining.indexOf('\n', last);
      }
      remaining = remaining.substring(last);
    });

    input.on('end', () => {
      if (remaining.length > 0) {
        func(remaining, records);
      }
      resolve(records);
    });
  };

  const input = fs.createReadStream(filename);
  readLines(input, func);
}));

module.exports = parse;

Thanks in advance!提前致谢!

Perhaps this will demonstrate for you how a try/catch will work with when using await.也许这将向您展示在使用 await 时 try/catch 将如何工作。 When a promise is rejected it will throw the resulting value.当 promise 被rejected时,它将throw结果值。 If the underlying promise resolves it will return that value.如果底层 promise resolves ,它将返回该值。

 (async () => { try { const val1 = await Promise.resolve('resolved val'); const val2 = await Promise.reject('reject val'); console.log(val1); } catch (err) { console.error(err); } })();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM