buddy

node MVC discord bot
Log | Files | Refs | README

DiscordAPIError.js (1780B)


      1 'use strict';
      2 
      3 /**
      4  * Represents an error from the Discord API.
      5  * @extends Error
      6  */
      7 class DiscordAPIError extends Error {
      8   constructor(path, error, method, status) {
      9     super();
     10     const flattened = this.constructor.flattenErrors(error.errors || error).join('\n');
     11     this.name = 'DiscordAPIError';
     12     this.message = error.message && flattened ? `${error.message}\n${flattened}` : error.message || flattened;
     13 
     14     /**
     15      * The HTTP method used for the request
     16      * @type {string}
     17      */
     18     this.method = method;
     19 
     20     /**
     21      * The path of the request relative to the HTTP endpoint
     22      * @type {string}
     23      */
     24     this.path = path;
     25 
     26     /**
     27      * HTTP error code returned by Discord
     28      * @type {number}
     29      */
     30     this.code = error.code;
     31 
     32     /**
     33      * The HTTP status code
     34      * @type {number}
     35      */
     36     this.httpStatus = status;
     37   }
     38 
     39   /**
     40    * Flattens an errors object returned from the API into an array.
     41    * @param {Object} obj Discord errors object
     42    * @param {string} [key] Used internally to determine key names of nested fields
     43    * @returns {string[]}
     44    * @private
     45    */
     46   static flattenErrors(obj, key = '') {
     47     let messages = [];
     48 
     49     for (const [k, v] of Object.entries(obj)) {
     50       if (k === 'message') continue;
     51       const newKey = key ? (isNaN(k) ? `${key}.${k}` : `${key}[${k}]`) : k;
     52 
     53       if (v._errors) {
     54         messages.push(`${newKey}: ${v._errors.map(e => e.message).join(' ')}`);
     55       } else if (v.code || v.message) {
     56         messages.push(`${v.code ? `${v.code}: ` : ''}${v.message}`.trim());
     57       } else if (typeof v === 'string') {
     58         messages.push(v);
     59       } else {
     60         messages = messages.concat(this.flattenErrors(v, newKey));
     61       }
     62     }
     63 
     64     return messages;
     65   }
     66 }
     67 
     68 module.exports = DiscordAPIError;