正确捕获异步函数node.js

时间:2018-07-17 13:43:45

标签: javascript node.js asynchronous

我的尝试是:

我的server.js具有以下内容:

const app = express();
app.get('/*', loader(filePath, observer));

我尝试调用的文件有时会加载错误,并冒泡为uncaughtExceptions,从而重新启动服务器。我需要以某种方式将其抓到{}中

export default (htmlFilePath, observer) => async (req, res) => {
    try {
      .......
      .......
      .......

        const markupStream = renderToNodeStream(
          <Provider store={store}>
            <ConnectedRouter history={history} location={context}>
              <App/>
            </ConnectedRouter>
          </Provider>
        );

        if (context.url) {
          return res.redirect(301, context.url)
        }

        return fs.createReadStream(htmlFilePath)
          .pipe(htmlReplace('#root', markupStream))
          .pipe(replaceStream('__SERVER_DATA__', serialize(store.getState())))
          .pipe(res);
      } catch (err) {
        const errMarkup = renderToNodeStream(
          <Provider store={store}>
            <ConnectedRouter history={history} location={context}>
              <Error500 error={err}/>
            </ConnectedRouter>
          </Provider>
        );

        logger.log({
          level: 'error',
          message: `Rendering ${req.originalUrl} fallback to Error render method`,
          ...{
            errorMessage: err.message,
            stack: err.stack
          }
        });

        return fs.createReadStream(htmlFilePath)
          .pipe(htmlReplace('#root', errMarkup))
          .pipe(res.status(500));
      } finally {
        logger.info(`Request finished ${req.originalUrl} :: ${res.statusCode}`)
        end({ route: path, componentName: componentNames[0], code: res.statusCode })
        logger.profile(profileMsg);
      }
}

什么是正确的方法?在执行().catch(err之前,我的问题是我总是得到uncaughtException,但从未在函数内的try{} catch{}中陷入困境

2 个答案:

答案 0 :(得分:2)

在使用async快速中间件时,为了捕获任何拒绝并将该拒绝传递给快速错误处理程序,您需要一个包装器:

async-handler.js

const asyncHandler = fn => (req, res, next) => {
    return Promise
        .resolve(fn(req, res, next))
        .catch(next);
};

module.exports = asyncHandler;

ssr-stream.js

const ssrStream = (htmlFilePath, observer) => async (req, res) => {
    // If you wrap this middleware with asyncHandler
    // No need try/catch, you can let it bubble up, and it will go to express error middleware
    // Of course you can do it, and handle the custom error here, and let it bubble up for generic errors.
}

export default ssrStream;

index.js

const app = express();
const asyncHandler = require('./async-handler');
const loader = require('./ssr-stream');

// Wrap your async function, with asyncHandler
app.get('/foo', asyncHandler(async(req, res) => {
    throw new Error('Foo'); // This will go to the express error middleware
}));

app.get('/*', asyncHandler(loader(filePath, observer)));

app.use((err, req, res, next) => {

    // Handle the error type, and set the correct status code
    const status = 500;
    res
        .status(status)
        .end(err.message);
});

答案 1 :(得分:-1)

您应该在函数表达式中检查它,而不是在函数声明中检查它。在函数本身中,只要有错误就抛出。然后,将其包装在try / catch块中:

catch

还可以在异步函数之后直接链接await ssrStream(htmlFilePath, observer) .catch(e => // handle error here); (本质上是一个承诺):

n = np.array([     0,      1,      2, 3])
df = df.iloc[n]
print (df)
               Open     High      Low    Close  Adj Close   Volume
2007-06-18  0.33979  0.33979  0.33979  0.33979    0.33979  1591888
2007-06-29  0.33074  0.33074  0.33074  0.33074    0.33074    88440
2007-06-20  0.33526  0.33526  0.33526  0.33526    0.33526     3538
2007-06-21  0.32113  0.32113  0.32113  0.32113    0.32113     3550
相关问题