@twilio-labs/serverless-api
Version:
API-wrapper for the Twilio Serverless API
63 lines (62 loc) • 2.37 kB
JavaScript
// import { } from 'got';
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClientApiError = exports.convertApiErrorsAndThrow = exports.filterUrl = void 0;
const source_1 = require("got/dist/source");
const url_1 = require("url");
function toTwilioApiError(response) {
if (typeof response !== 'object') {
return undefined;
}
return response;
}
/**
* Explictly removes username and password from a URL.
* @param unfilteredUrl any URL string
*/
function filterUrl(unfilteredUrl) {
if (!unfilteredUrl) {
return '';
}
const url = new url_1.URL(unfilteredUrl);
url.username = '';
url.password = '';
return url.toString();
}
exports.filterUrl = filterUrl;
/**
* Throws the error it receives and if it's an HTTP Error it will convert it to a ClientApiError
*
*/
function convertApiErrorsAndThrow(err) {
if (err.name === 'HTTPError') {
err = new ClientApiError(err);
}
throw err;
}
exports.convertApiErrorsAndThrow = convertApiErrorsAndThrow;
/**
* An Error wrapper to provide more useful error information without exposing credentials
*/
class ClientApiError extends Error {
constructor(requestError) {
var _a, _b, _c;
super('Unknown Error');
if (requestError instanceof source_1.RequestError) {
const twilioApiErrorInfo = toTwilioApiError((_a = requestError.response) === null || _a === void 0 ? void 0 : _a.body);
const message = (twilioApiErrorInfo === null || twilioApiErrorInfo === void 0 ? void 0 : twilioApiErrorInfo.message) || requestError.message;
Error.captureStackTrace(this, this.constructor);
this.name = requestError.name;
this.message = message;
this.code = (twilioApiErrorInfo === null || twilioApiErrorInfo === void 0 ? void 0 : twilioApiErrorInfo.code) || ((_b = requestError.response) === null || _b === void 0 ? void 0 : _b.statusCode);
this.url = filterUrl((_c = requestError.response) === null || _c === void 0 ? void 0 : _c.requestUrl);
if (requestError.name === 'HTTPError' && twilioApiErrorInfo) {
this.name = 'TwilioApiError';
this.details = {
...twilioApiErrorInfo,
};
}
}
}
}
exports.ClientApiError = ClientApiError;
;