UNPKG

1.99 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3/**
4 * HttpError extends the Error object, and is thrown wheenever servers emit
5 * HTTP errors.
6 *
7 * It has a response property, allowing users to find out more about the
8 * nature of the error.
9 *
10 * @constructor
11 * @param {Response} response
12 */
13class HttpError extends Error {
14 constructor(response) {
15 super('HTTP error ' + response.status);
16 this.response = response;
17 this.status = response.status;
18 }
19}
20exports.HttpError = HttpError;
21/**
22 * Problem extends the HttpError object. If a server emits a HTTP error, and
23 * the response body's content-type is application/problem+json.
24 *
25 * application/problem+json is defined in RFC7807 and provides a standardized
26 * way to describe error conditions by a HTTP server.
27 *
28 * @constructor
29 * @param {Response} response
30 * @param {object} problemBody
31 */
32class Problem extends HttpError {
33 constructor(response, problemBody) {
34 super(response);
35 this.body = problemBody;
36 if (this.body.title) {
37 this.message = 'HTTP Error ' + this.status + ': ' + this.body.title;
38 }
39 }
40}
41exports.Problem = Problem;
42/**
43 * This function creates problems, not unlike the the author of this file.
44 *
45 * It takes a Fetch Response object, and returns a HttpError. If the HTTP
46 * response has a type of application/problem+json it will return a Problem
47 * object.
48 *
49 * Because parsing the response might be asynchronous, the function returns
50 * a Promise resolving in either object.
51 */
52async function problemFactory(response) {
53 const contentType = response.headers.get('Content-Type');
54 if (contentType && contentType.match(/^application\/problem\+json/i)) {
55 const problemBody = await response.json();
56 return new Problem(response, problemBody);
57 }
58 else {
59 return new HttpError(response);
60 }
61}
62exports.default = problemFactory;
63//# sourceMappingURL=http-error.js.map
\No newline at end of file