节点try / catch块仍然冒泡

时间:2018-08-31 09:42:41

标签: node.js reactjs express react-dom-server

我遇到了捕获服务器渲染错误的问题,这对我来说很奇怪,它到达了catch语句,但是仍然冒泡并崩溃并出现Uncaught异常。

这是我的函数的精简版:

export default (htmlFilePath, observer) => async (req, res) => {
  try {
    const { state } = await rehydrate.dispatchRequired(store, [
      setMobileDetect.bind(null, mobileDetect),
      ...REQUIRED_ACTIONS,
    ]);
    // Will dispatch the required data through the store,
    // the returned value is not important
    const matches = rehydrate.getMatches(req, state);
    let status = 200;

    componentNames = matches.map(
      ({ route }) => route.component.displayName,
    );

    await rehydrate.rehydrate(matches, store, state);

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

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

    // if no routes match we return 404
    if (!matches.length) {
      status = 404;
    }

    return fs
      .createReadStream(htmlFilePath)
      .pipe(htmlReplace("#root", markupStream))
      .pipe(
        replaceStream("__SERVER_DATA__", serialize(store.getState())),
      )
      .pipe(res.status(status));
  } 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块返回500个错误的模块,但是由于 markupStream()

中未捕获的异常,节点实例崩溃了

更新:根据要求,这里是日志: https://pastebin.com/A4vL8zcc

1 个答案:

答案 0 :(得分:1)

由于您使用的是renderToNodeStream,因此只有在尝试从流中读取内容时才进行实际渲染,这从日志中的堆栈跟踪中可以明显看出:

TypeError: Cannot read property 'length' of undefined
    at NotFoundPage.render (~/server/dist/loader.js:43889:23)
    at processChild (~/node_modules/react-dom/cjs/react-dom-server.node.development.js:2207:18)
    at resolve (~/node_modules/react-dom/cjs/react-dom-server.node.development.js:2064:5)
    at ReactDOMServerRenderer.render (~/node_modules/react-dom/cjs/react-dom-server.node.development.js:2349:22)
    at ReactDOMServerRenderer.read (~/node_modules/react-dom/cjs/react-dom-server.node.development.js:2323:19)
    at ReactMarkupReadableStream._read (~/node_modules/react-dom/cjs/react-dom-server.node.development.js:2735:38)
    at ReactMarkupReadableStream.Readable.read (_stream_readable.js:449:10)
    at flow (_stream_readable.js:853:34)
 => at resume_ (_stream_readable.js:835:3)
    at process._tickCallback (internal/process/next_tick.js:114:19)

这意味着所有错误仅在流的读取/配管过程中发生,即在您的HTTP框架中发生,对于您的try / catch来说,看到它们为时已晚。

您可能想使用renderToString,或检测返回的流以进行错误处理。