Joelgullander
Joelgullander

Reputation: 1684

Node.js createReadStream error handling

I'm running a SSR React node.js server and I need some suggestions on how to solve my problem. My node.js server crashes/restarts on error like window is not defined etc instead of just logging & printing out a 500 error message.

Here is my stream:

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

I thought my catch would get those errors but apparently it's no, can someone help me point me in the right direction?

UPDATE: 1 I'm currently attemping:

const readStream = fs.createReadStream(htmlFilePath);

// Should hopefully catch the errors
readStream.on('error', function(err) {
  res.end(err);
});

return readStream.pipe(htmlReplace('#root', markupStream))
  .pipe(replaceStream('__SERVER_DATA__', serialize(store.getState())))
  .pipe(res);

Upvotes: 0

Views: 5251

Answers (1)

Tushar Nikam
Tushar Nikam

Reputation: 624

You need to create stream first before return it so that you use its error callback function:

var readStream = fs.createReadStream(filename);
  readStream.on('error', function(err) {
    res.end(err);
  });
return readStream

Upvotes: 3

Related Questions