errors.js 2.2 KB

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