How to catch and process errors thrown during Strapi startup

Hi. I have a custom middleware error handler that catches, and processes errors (sends logs to an external service). Sometimes however Strapi errors out on start - e.g. if there is an error related to DB. This error logs are not caught by the middleware, and I’ve spent almost 2 days trying to figure out how can I catch and process them. And I couldn’t find a way. I’ve tried things like

process.on('uncaughtException', () => {...});

I’ve tried to somehow pass custom transports to winston, I’ve tried to wrap strapi().start() in a try catch, I’ve even tried to intercept node process to overwrite strapi.log methods. Everything I’ve tried failed.

Any ideas?

This topic has been created from a Discord post (1291356344439410751) to give it more visibility.
It will be on Read-Only mode here.
Join the conversation on Discord

I’ve read the source code, and based on it I added

// /config/logger.js
const { transports } = require('winston');

const consoleTransport = new transports.Console();
const fileTransport = new transports.File({ filename: 'winstontest.log' });

module.exports = {
  transports: [consoleTransport, fileTransport],
};

Then I’ve found a method that’s called when server startup fails:

  stopWithError(err, customMessage) {
    this.log.debug(`⛔️ Server wasn't able to start properly.`);
    if (customMessage) {
      this.log.error(customMessage);
    }
    this.log.error(err);

    this.log.debug(`I am not sure why it does not work...`);
    
    return this.stop();
  }

I don’t know why, but only the first debug is logged to the file, the second one and the errors are visible in the console, but not stored in a file

I guess it could be caused by the node process being killed before the log is asynchronously stored in the file…