diff --git a/lib/errors.js b/lib/errors.js index cf5ddba6..5bf6b012 100644 --- a/lib/errors.js +++ b/lib/errors.js @@ -1,10 +1,10 @@ 'use strict' -const url = require('url') +const { URL } = require('node:url') function packageName (href) { try { - let basePath = new url.URL(href).pathname.slice(1) + let basePath = new URL(href).pathname.slice(1) if (!basePath.match(/^-/)) { basePath = basePath.split('/') var index = basePath.indexOf('_rewrite') @@ -15,7 +15,7 @@ function packageName (href) { } return decodeURIComponent(basePath[index]) } - } catch (_) { + } catch { // this is ok } } @@ -24,16 +24,16 @@ class HttpErrorBase extends Error { constructor (method, res, body, spec) { super() this.name = this.constructor.name - this.headers = res.headers.raw() + this.headers = typeof res.headers?.raw === 'function' ? res.headers.raw() : res.headers this.statusCode = res.status this.code = `E${res.status}` this.method = method this.uri = res.url this.body = body this.pkgid = spec ? spec.toString() : packageName(res.url) + Error.captureStackTrace(this, this.constructor) } } -module.exports.HttpErrorBase = HttpErrorBase class HttpErrorGeneral extends HttpErrorBase { constructor (method, res, body, spec) { @@ -45,36 +45,36 @@ class HttpErrorGeneral extends HttpErrorBase { }${ (body && body.error) ? ' - ' + body.error : '' }` - Error.captureStackTrace(this, HttpErrorGeneral) } } -module.exports.HttpErrorGeneral = HttpErrorGeneral class HttpErrorAuthOTP extends HttpErrorBase { constructor (method, res, body, spec) { super(method, res, body, spec) this.message = 'OTP required for authentication' this.code = 'EOTP' - Error.captureStackTrace(this, HttpErrorAuthOTP) } } -module.exports.HttpErrorAuthOTP = HttpErrorAuthOTP class HttpErrorAuthIPAddress extends HttpErrorBase { constructor (method, res, body, spec) { super(method, res, body, spec) this.message = 'Login is not allowed from your IP address' this.code = 'EAUTHIP' - Error.captureStackTrace(this, HttpErrorAuthIPAddress) } } -module.exports.HttpErrorAuthIPAddress = HttpErrorAuthIPAddress class HttpErrorAuthUnknown extends HttpErrorBase { constructor (method, res, body, spec) { super(method, res, body, spec) this.message = 'Unable to authenticate, need: ' + res.headers.get('www-authenticate') - Error.captureStackTrace(this, HttpErrorAuthUnknown) } } -module.exports.HttpErrorAuthUnknown = HttpErrorAuthUnknown + +module.exports = { + HttpErrorBase, + HttpErrorGeneral, + HttpErrorAuthOTP, + HttpErrorAuthIPAddress, + HttpErrorAuthUnknown, +} diff --git a/test/errors.js b/test/errors.js index 26cad0df..cfa1197b 100644 --- a/test/errors.js +++ b/test/errors.js @@ -271,4 +271,8 @@ t.test('Unexpected www-authenticate error', t => { ) }) -t.test('retries certain types') +t.test('error can take headers object', (t) => { + t.strictSame(new errors.HttpErrorBase('GET', { headers: { a: 1 } }).headers, { a: 1 }) + t.strictSame(new errors.HttpErrorBase('GET', { }).headers, undefined) + t.end() +})