buddy

node MVC discord bot
Log | Files | Refs | README

DJSError.js (1634B)


      1 'use strict';
      2 
      3 // Heavily inspired by node's `internal/errors` module
      4 
      5 const kCode = Symbol('code');
      6 const messages = new Map();
      7 
      8 /**
      9  * Extend an error of some sort into a DiscordjsError.
     10  * @param {Error} Base Base error to extend
     11  * @returns {DiscordjsError}
     12  */
     13 function makeDiscordjsError(Base) {
     14   return class DiscordjsError extends Base {
     15     constructor(key, ...args) {
     16       super(message(key, args));
     17       this[kCode] = key;
     18       if (Error.captureStackTrace) Error.captureStackTrace(this, DiscordjsError);
     19     }
     20 
     21     get name() {
     22       return `${super.name} [${this[kCode]}]`;
     23     }
     24 
     25     get code() {
     26       return this[kCode];
     27     }
     28   };
     29 }
     30 
     31 /**
     32  * Format the message for an error.
     33  * @param {string} key Error key
     34  * @param {Array<*>} args Arguments to pass for util format or as function args
     35  * @returns {string} Formatted string
     36  */
     37 function message(key, args) {
     38   if (typeof key !== 'string') throw new Error('Error message key must be a string');
     39   const msg = messages.get(key);
     40   if (!msg) throw new Error(`An invalid error message key was used: ${key}.`);
     41   if (typeof msg === 'function') return msg(...args);
     42   if (args === undefined || args.length === 0) return msg;
     43   args.unshift(msg);
     44   return String(...args);
     45 }
     46 
     47 /**
     48  * Register an error code and message.
     49  * @param {string} sym Unique name for the error
     50  * @param {*} val Value of the error
     51  */
     52 function register(sym, val) {
     53   messages.set(sym, typeof val === 'function' ? val : String(val));
     54 }
     55 
     56 module.exports = {
     57   register,
     58   Error: makeDiscordjsError(Error),
     59   TypeError: makeDiscordjsError(TypeError),
     60   RangeError: makeDiscordjsError(RangeError),
     61 };