0

I'm having issues catching my server-rendering errors, the odd this for me is that it reaches the catch statement however it still bubbles up and crashes & gets Uncaught exception.

Here is a stripped version of my function:

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);
  }
};

I want my catch block to return the module for 500 errors but the node instance is crashing because of the uncaught exception from markupStream()

UPDATE: As requested here's the log: https://pastebin.com/A4vL8zcc

Joelgullander
  • 1,624
  • 2
  • 20
  • 46

1 Answers1

1

Since you're using renderToNodeStream, the actual rendering is not done until something attempts to read from the stream, as evident from the stack trace in your log:

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)

This means any errors only happen during reading/piping of the stream, i.e. in your HTTP framework, which is too late for your try/catch to see them.

You probably want to use renderToString, or instrument the stream you return to have error handling.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • Yeah I had renderToString before and I wanted to upgrade to renderToNodeStream. I'll try read up on how to error handle renderToNodeStream, fairly new to node so I really appreciate the direction you gave me. – Joelgullander Aug 31 '18 at 10:05
  • Do you think it's possible to reach the catch block if adding an error event to the renderToNodeStream or createReadStream or do I need to return directly in that event? – Joelgullander Aug 31 '18 at 10:51
  • You'll need to deal with it in the stream's error event. Control has already been transferred away from that function by that time. – AKX Aug 31 '18 at 13:45