import { ErrorRequestHandler, Request, Response } from "express"; import { HttpError } from "http-errors"; import { logError } from '../lib/logger'; /** * Final error handler that executes when an unhandled error occurs. * This prevents the server from crashing and ensures proper response handling. * * @param err - HTTP error object * @param req - Express request object * @param res - Express response object * @param next - Express next function */ export const finalErrorRouter:ErrorRequestHandler = async (err:HttpError, req, res, next) => { const errorLogText:string = JSON.stringify({ message:err.message, name:err.name, stack:err.stack }); logError("server error", `${err.status}; n${errorLogText}`); // `headersSent` will be TRUE if the router where the error occurred has already sent headers // If we try to set them again, it will throw an error and CRASH THE SERVER - we must prevent this if(!res.headersSent) { res.status(err.status); res.setHeader('Content-Type', "text/html"); res.end(`unhandled server error`); } else { // If `end` hasn't been called - call it to finish processing the request // Otherwise the connection will remain open until timeout if(!res.writableEnded) { res.end(); } } };