index.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { Deprecation } from "deprecation";
  2. import once from "once";
  3. const logOnceCode = once((deprecation) => console.warn(deprecation));
  4. const logOnceHeaders = once((deprecation) => console.warn(deprecation));
  5. /**
  6. * Error with extra properties to help with debugging
  7. */
  8. export class RequestError extends Error {
  9. constructor(message, statusCode, options) {
  10. super(message);
  11. // Maintains proper stack trace (only available on V8)
  12. /* istanbul ignore next */
  13. if (Error.captureStackTrace) {
  14. Error.captureStackTrace(this, this.constructor);
  15. }
  16. this.name = "HttpError";
  17. this.status = statusCode;
  18. let headers;
  19. if ("headers" in options && typeof options.headers !== "undefined") {
  20. headers = options.headers;
  21. }
  22. if ("response" in options) {
  23. this.response = options.response;
  24. headers = options.response.headers;
  25. }
  26. // redact request credentials without mutating original request options
  27. const requestCopy = Object.assign({}, options.request);
  28. if (options.request.headers.authorization) {
  29. requestCopy.headers = Object.assign({}, options.request.headers, {
  30. authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]"),
  31. });
  32. }
  33. requestCopy.url = requestCopy.url
  34. // client_id & client_secret can be passed as URL query parameters to increase rate limit
  35. // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
  36. .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]")
  37. // OAuth tokens can be passed as URL query parameters, although it is not recommended
  38. // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
  39. .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
  40. this.request = requestCopy;
  41. // deprecations
  42. Object.defineProperty(this, "code", {
  43. get() {
  44. logOnceCode(new Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
  45. return statusCode;
  46. },
  47. });
  48. Object.defineProperty(this, "headers", {
  49. get() {
  50. logOnceHeaders(new Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`."));
  51. return headers || {};
  52. },
  53. });
  54. }
  55. }