UNPKG

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