libflitter/errors/RunLevelErrorHandler.js

/**
 * @module libflitter/errors/RunLevelErrorHandler
 */

/**
 * Class for handling errors that make it to the top-level of
 * the Flitter runtime.
 */
class RunLevelErrorHandler {
    /**
     * Get the error handler function. This is safe to
     * pass into a .catch() statement.
     * e.g. `flitter.run().catch(rleh.handle)`
     * @type function(...[*]=)
     */
    get handle() {
        return e => {
            this.display(e)
            process.exit(1)
        }
    }

    /**
     * Display the error in the console.
     * @param {Error} e
     */
    display(e) {
        try {
            const color = require('colors/safe')
            console.error('')
            console.error(`${color.redBG('                                ')}`)
            console.error(`${color.redBG('    UNCAUGHT TOP-LEVEL ERROR    ')}`)
            console.error(`${color.redBG('                                ')}`)
            if ( e.component ) console.error(`${color.blackBG(color.red('Component: '+e.component))}`)
            console.error('')
            console.error(`${e.constructor ? e.constructor.name : e.name}`)
            console.error(color.red(`---------------------------------------------------`))
            console.error(e.stack)
        } catch (display_e) {
            // The error display encountered an error...
            // just throw the original so it makes it out
            throw e
        }
    }
}

module.exports = exports = RunLevelErrorHandler