errors.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. 'use strict'
  2. const { URL } = require('node:url')
  3. function packageName (href) {
  4. try {
  5. let basePath = new URL(href).pathname.slice(1)
  6. if (!basePath.match(/^-/)) {
  7. basePath = basePath.split('/')
  8. var index = basePath.indexOf('_rewrite')
  9. if (index === -1) {
  10. index = basePath.length - 1
  11. } else {
  12. index++
  13. }
  14. return decodeURIComponent(basePath[index])
  15. }
  16. } catch {
  17. // this is ok
  18. }
  19. }
  20. class HttpErrorBase extends Error {
  21. constructor (method, res, body, spec) {
  22. super()
  23. this.name = this.constructor.name
  24. this.headers = typeof res.headers?.raw === 'function' ? res.headers.raw() : res.headers
  25. this.statusCode = res.status
  26. this.code = `E${res.status}`
  27. this.method = method
  28. this.uri = res.url
  29. this.body = body
  30. this.pkgid = spec ? spec.toString() : packageName(res.url)
  31. Error.captureStackTrace(this, this.constructor)
  32. }
  33. }
  34. class HttpErrorGeneral extends HttpErrorBase {
  35. constructor (method, res, body, spec) {
  36. super(method, res, body, spec)
  37. this.message = `${res.status} ${res.statusText} - ${
  38. this.method.toUpperCase()
  39. } ${
  40. this.spec || this.uri
  41. }${
  42. (body && body.error) ? ' - ' + body.error : ''
  43. }`
  44. }
  45. }
  46. class HttpErrorAuthOTP extends HttpErrorBase {
  47. constructor (method, res, body, spec) {
  48. super(method, res, body, spec)
  49. this.message = 'OTP required for authentication'
  50. this.code = 'EOTP'
  51. }
  52. }
  53. class HttpErrorAuthIPAddress extends HttpErrorBase {
  54. constructor (method, res, body, spec) {
  55. super(method, res, body, spec)
  56. this.message = 'Login is not allowed from your IP address'
  57. this.code = 'EAUTHIP'
  58. }
  59. }
  60. class HttpErrorAuthUnknown extends HttpErrorBase {
  61. constructor (method, res, body, spec) {
  62. super(method, res, body, spec)
  63. this.message = 'Unable to authenticate, need: ' + res.headers.get('www-authenticate')
  64. }
  65. }
  66. module.exports = {
  67. HttpErrorBase,
  68. HttpErrorGeneral,
  69. HttpErrorAuthOTP,
  70. HttpErrorAuthIPAddress,
  71. HttpErrorAuthUnknown,
  72. }