Exit the process gracefully when a stranger comes to town

    Javascript

    Typescript

    1. process.on('uncaughtException', (error: Error) => {
    2. errorManagement.handler.handleError(error);
    3. if(!errorManagement.handler.isTrustedError(error))
    4. process.exit(1)
    5. });
    6. // centralized error object that derives from Node’s Error
    7. export class AppError extends Error {
    8. constructor(description: string, isOperational: boolean) {
    9. Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
    10. this.isOperational = isOperational;
    11. Error.captureStackTrace(this);
    12. }
    13. }
    14. // centralized error handler encapsulates error-handling related logic
    15. class ErrorHandler {
    16. public async handleError(err: Error): Promise<void> {
    17. await logger.logError(err);
    18. await sendMailToAdminIfCritical();
    19. await determineIfOperationalError();
    20. };
    21. public isTrustedError(error: Error) {
    22. if (error instanceof AppError) {
    23. return error.isOperational;
    24. }
    25. return false;
    26. }
    27. }

    From the blog: JS Recipes

    1. Let the application crash and restart it.
    2. Handle all possible errors and never crash.

    From Node.js official documentation