errors.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 'use strict';
  2. const urlLib = require('url');
  3. const http = require('http');
  4. const PCancelable = require('p-cancelable');
  5. const is = require('@sindresorhus/is');
  6. class GotError extends Error {
  7. constructor(message, error, opts) {
  8. super(message);
  9. Error.captureStackTrace(this, this.constructor);
  10. this.name = 'GotError';
  11. if (!is.undefined(error.code)) {
  12. this.code = error.code;
  13. }
  14. Object.assign(this, {
  15. host: opts.host,
  16. hostname: opts.hostname,
  17. method: opts.method,
  18. path: opts.path,
  19. protocol: opts.protocol,
  20. url: opts.href
  21. });
  22. }
  23. }
  24. module.exports.GotError = GotError;
  25. module.exports.CacheError = class extends GotError {
  26. constructor(error, opts) {
  27. super(error.message, error, opts);
  28. this.name = 'CacheError';
  29. }
  30. };
  31. module.exports.RequestError = class extends GotError {
  32. constructor(error, opts) {
  33. super(error.message, error, opts);
  34. this.name = 'RequestError';
  35. }
  36. };
  37. module.exports.ReadError = class extends GotError {
  38. constructor(error, opts) {
  39. super(error.message, error, opts);
  40. this.name = 'ReadError';
  41. }
  42. };
  43. module.exports.ParseError = class extends GotError {
  44. constructor(error, statusCode, opts, data) {
  45. super(`${error.message} in "${urlLib.format(opts)}": \n${data.slice(0, 77)}...`, error, opts);
  46. this.name = 'ParseError';
  47. this.statusCode = statusCode;
  48. this.statusMessage = http.STATUS_CODES[this.statusCode];
  49. }
  50. };
  51. module.exports.HTTPError = class extends GotError {
  52. constructor(statusCode, statusMessage, headers, opts) {
  53. if (statusMessage) {
  54. statusMessage = statusMessage.replace(/\r?\n/g, ' ').trim();
  55. } else {
  56. statusMessage = http.STATUS_CODES[statusCode];
  57. }
  58. super(`Response code ${statusCode} (${statusMessage})`, {}, opts);
  59. this.name = 'HTTPError';
  60. this.statusCode = statusCode;
  61. this.statusMessage = statusMessage;
  62. this.headers = headers;
  63. }
  64. };
  65. module.exports.MaxRedirectsError = class extends GotError {
  66. constructor(statusCode, redirectUrls, opts) {
  67. super('Redirected 10 times. Aborting.', {}, opts);
  68. this.name = 'MaxRedirectsError';
  69. this.statusCode = statusCode;
  70. this.statusMessage = http.STATUS_CODES[this.statusCode];
  71. this.redirectUrls = redirectUrls;
  72. }
  73. };
  74. module.exports.UnsupportedProtocolError = class extends GotError {
  75. constructor(opts) {
  76. super(`Unsupported protocol "${opts.protocol}"`, {}, opts);
  77. this.name = 'UnsupportedProtocolError';
  78. }
  79. };
  80. module.exports.CancelError = PCancelable.CancelError;