libflitter/errors/FlitterError.js

/**
 * @module libflitter/errors/FlitterError
 */

/**
 * An error class that provides some extra functionality specific to Flitter.
 * @extends Error
 */
class FlitterError extends Error {

    /**
     * Instantiate the error. Set a default component name and message.
     * @param {string} msg
     * @param {...*} args
     */
    constructor(msg = "Flitter encountered an error.", ...args){
        super(msg, ...args)

        /**
         * Name of the Flitter component that encountered an error.
         * @type {string} ["the requested component"]
         */
        this.component = "the requested component"
    }

    /**
     * Creates an error message for missing services by name.
     * @param {string|Array<string>} service - the name of the service or array of services that are required
     * @returns {module:libflitter/errors/FlitterError~FlitterError} - instance of self to allow chaining
     */
    required(service){
        let message = 'Flitter: The following service or services are required for '+this.unit()+' to start: '
        if ( Array.isArray(service) ){
            for ( let key in service ){
                message += service[key]+', '
            }
            
            message = message.slice(0, -2)
        }
        else message += service
        
        this.message = message
        
        return this // allow chaining
    }

    /**
     * Get or set the component name.
     * @param {string|null} [name = null] - name of the component
     * @returns {string|module:libflitter/errors/FlitterError~FlitterError} - If no name is provided, returns the current value of {@link module:libflitter/errors/FlitterError~FlitterError#component}. If a name is provided, returns an instance of self to allow chaining.
     */
    unit(name = null){
        if ( name === null ) return this.component
        else {
            this.component = name
            return this // allow chaining
        }
    }
    
}

module.exports = exports = FlitterError