axios-exception-handler
Version:
Exception Handler for Axios
70 lines (65 loc) • 2.18 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var axios = require('axios');
var AxiosExceptionHandler = /** @class */ (function () {
/**
* @param response AxiosResponse
*/
function AxiosExceptionHandler(response) {
this.exceptions = new Map();
this.unHandledMessage = "Unhandled exception";
this.response = response;
this.exceptions = new Map();
}
/**
* Add a case
* @param code HTTP Status Code to handle
* @param message Error message to throw
*/
AxiosExceptionHandler.prototype.addCase = function (code, message) {
this.exceptions.set(code, message);
return this;
};
/**
* Add multiple cases
* @param {Number[]} codes HTTP Status Codes to handle
* @param {String} message Error message to throw
*/
AxiosExceptionHandler.prototype.addCases = function (codes, message) {
var _this = this;
codes.forEach(function (code) { return _this.addCase(code, message); });
return this;
};
/**
* Add a default case
* @param message Error message to throw
* @default "Unhandled exception"
*/
AxiosExceptionHandler.prototype.addDefaultCase = function (message) {
this.unHandledMessage = message;
return this;
};
/**
* Handle the exception
* @returns AxiosResponse<T>
*/
AxiosExceptionHandler.prototype.handle = function () {
var _a;
if (!(this.response instanceof axios.AxiosError)) {
if (this.response instanceof Error)
throw this.response;
return this.response;
}
var status = this.response && ((_a = this.response.response) === null || _a === void 0 ? void 0 : _a.status);
if (status && this.exceptions.has(status)) {
throw new Error(this.exceptions.get(status));
}
throw new Error(this.unHandledMessage);
};
return AxiosExceptionHandler;
}());
function ExceptionHandler(response) {
return new AxiosExceptionHandler(response);
}
exports.ExceptionHandler = ExceptionHandler;
exports.default = ExceptionHandler;