UNPKG

@sendgrid/helpers

Version:

Twilio SendGrid NodeJS internal helpers

62 lines (51 loc) 1.25 kB
'use strict'; /** * Response error class */ class ResponseError extends Error { /** * Constructor */ constructor(response) { //Super super(); //Extract data from response const { headers, status, statusText, data } = response; //Set data this.code = status; this.message = statusText; this.response = { headers, body: data }; //Capture stack trace if (!this.stack) { Error.captureStackTrace(this, this.constructor); } //Clean up stack trace const regex = new RegExp(process.cwd() + '/', 'gi'); this.stack = this.stack.replace(regex, ''); } /** * Convert to string */ toString() { const { body } = this.response; let err = `${this.message} (${this.code})`; if (body && Array.isArray(body.errors)) { body.errors.forEach(error => { const message = error.message; const field = error.field; const help = error.help; err += `\n ${message}\n ${field}\n ${help}`; }); } return err; } /** * Convert to simple object for JSON responses */ toJSON() { const { message, code, response } = this; return { message, code, response }; } } //Export module.exports = ResponseError;