From d353d7cce7a719edd5d9ad27ab4aa025e3dd930e Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Mon, 27 Dec 2021 19:30:20 +0100 Subject: [PATCH] Throw a special error subclass when the public IP address could not be found --- browser.js | 9 ++++++++- index.d.ts | 5 +++++ index.js | 12 +++++++++--- readme.md | 8 ++++++++ 4 files changed, 30 insertions(+), 4 deletions(-) diff --git a/browser.js b/browser.js index cbcd673..5983c6e 100644 --- a/browser.js +++ b/browser.js @@ -11,6 +11,13 @@ export class CancelError extends Error { } } +export class IpNotFoundError extends Error { + constructor(options) { + super('Could not get the public IP address', options); + this.name = 'IpNotFoundError'; + } +} + const defaults = { timeout: 5000, }; @@ -83,7 +90,7 @@ const queryHttps = (version, options) => { } } - throw new Error('Could not find your IP address', {cause: lastError}); + throw new IpNotFoundError({cause: lastError}); })(); promise.cancel = () => { diff --git a/index.d.ts b/index.d.ts index 208395b..c9f8ed6 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,3 +1,8 @@ +/** +Thrown when the public IP address could not be found. +*/ +export class IpNotFoundError extends Error {} + export interface Options { /** Use a HTTPS check using the [icanhazip.com](https://github.com/major/icanhaz) service instead of the DNS query. [ipify.org](https://www.ipify.org) is used as a fallback if `icanhazip.com` fails. This check is much more secure and tamper-proof, but also a lot slower. diff --git a/index.js b/index.js index 9e3ed88..2f089e5 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,13 @@ import dns from 'dns-socket'; import got, {CancelError} from 'got'; import isIp from 'is-ip'; +export class IpNotFoundError extends Error { + constructor(options) { + super('Could not get the public IP address', options); + this.name = 'IpNotFoundError'; + } +} + const defaults = { timeout: 5000, onlyHttps: false, @@ -129,7 +136,7 @@ const queryDns = (version, options) => { socket.destroy(); - throw new Error('Could not find your IP address', {cause: lastError}); + throw new IpNotFoundError({cause: lastError}); })(); promise.cancel = () => { @@ -183,8 +190,7 @@ const queryHttps = (version, options) => { } } - const errorDescription = lastError ? `: ${lastError.message}` : ''; - throw new Error(`Could not find your IP address${errorDescription}`, {cause: lastError}); + throw new IpNotFoundError({cause: lastError}); } catch (error) { // Don't throw a cancellation error for consistency with DNS if (!(error instanceof CancelError)) { diff --git a/readme.md b/readme.md index 4b46c19..05a198c 100644 --- a/readme.md +++ b/readme.md @@ -64,6 +64,14 @@ Default: `5000` The time in milliseconds until a request is considered timed out. +### IpNotFoundError + +Error thrown when the public IP address could not be found. + +### CancelError + +Error thrown when the operation was canceled. + ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus)