AxiosError.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict';
  2. var utils = require('../utils');
  3. /**
  4. * Create an Error with the specified message, config, error code, request and response.
  5. *
  6. * @param {string} message The error message.
  7. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  8. * @param {Object} [config] The config.
  9. * @param {Object} [request] The request.
  10. * @param {Object} [response] The response.
  11. * @returns {Error} The created error.
  12. */
  13. function AxiosError(message, code, config, request, response) {
  14. Error.call(this);
  15. this.message = message;
  16. this.name = 'AxiosError';
  17. code && (this.code = code);
  18. config && (this.config = config);
  19. request && (this.request = request);
  20. response && (this.response = response);
  21. }
  22. utils.inherits(AxiosError, Error, {
  23. toJSON: function toJSON() {
  24. return {
  25. // Standard
  26. message: this.message,
  27. name: this.name,
  28. // Microsoft
  29. description: this.description,
  30. number: this.number,
  31. // Mozilla
  32. fileName: this.fileName,
  33. lineNumber: this.lineNumber,
  34. columnNumber: this.columnNumber,
  35. stack: this.stack,
  36. // Axios
  37. config: this.config,
  38. code: this.code,
  39. status: this.response && this.response.status ? this.response.status : null
  40. };
  41. }
  42. });
  43. var prototype = AxiosError.prototype;
  44. var descriptors = {};
  45. [
  46. 'ERR_BAD_OPTION_VALUE',
  47. 'ERR_BAD_OPTION',
  48. 'ECONNABORTED',
  49. 'ETIMEDOUT',
  50. 'ERR_NETWORK',
  51. 'ERR_FR_TOO_MANY_REDIRECTS',
  52. 'ERR_DEPRECATED',
  53. 'ERR_BAD_RESPONSE',
  54. 'ERR_BAD_REQUEST',
  55. 'ERR_CANCELED'
  56. // eslint-disable-next-line func-names
  57. ].forEach(function(code) {
  58. descriptors[code] = {value: code};
  59. });
  60. Object.defineProperties(AxiosError, descriptors);
  61. Object.defineProperty(prototype, 'isAxiosError', {value: true});
  62. // eslint-disable-next-line func-names
  63. AxiosError.from = function(error, code, config, request, response, customProps) {
  64. var axiosError = Object.create(prototype);
  65. utils.toFlatObject(error, axiosError, function filter(obj) {
  66. return obj !== Error.prototype;
  67. });
  68. AxiosError.call(axiosError, error.message, code, config, request, response);
  69. axiosError.name = error.name;
  70. customProps && Object.assign(axiosError, customProps);
  71. return axiosError;
  72. };
  73. module.exports = AxiosError;