errors.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. 'use strict'
  2. const url = require('url')
  3. function packageName (href) {
  4. try {
  5. let basePath = new url.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 = res.headers.raw()
  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. }
  32. }
  33. module.exports.HttpErrorBase = HttpErrorBase
  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. Error.captureStackTrace(this, HttpErrorGeneral)
  45. }
  46. }
  47. module.exports.HttpErrorGeneral = HttpErrorGeneral
  48. class HttpErrorAuthOTP extends HttpErrorBase {
  49. constructor (method, res, body, spec) {
  50. super(method, res, body, spec)
  51. this.message = 'OTP required for authentication'
  52. this.code = 'EOTP'
  53. Error.captureStackTrace(this, HttpErrorAuthOTP)
  54. }
  55. }
  56. module.exports.HttpErrorAuthOTP = HttpErrorAuthOTP
  57. class HttpErrorAuthIPAddress extends HttpErrorBase {
  58. constructor (method, res, body, spec) {
  59. super(method, res, body, spec)
  60. this.message = 'Login is not allowed from your IP address'
  61. this.code = 'EAUTHIP'
  62. Error.captureStackTrace(this, HttpErrorAuthIPAddress)
  63. }
  64. }
  65. module.exports.HttpErrorAuthIPAddress = HttpErrorAuthIPAddress
  66. class HttpErrorAuthUnknown extends HttpErrorBase {
  67. constructor (method, res, body, spec) {
  68. super(method, res, body, spec)
  69. this.message = 'Unable to authenticate, need: ' + res.headers.get('www-authenticate')
  70. Error.captureStackTrace(this, HttpErrorAuthUnknown)
  71. }
  72. }
  73. module.exports.HttpErrorAuthUnknown = HttpErrorAuthUnknown