Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ CHANGELOG

* **Breaking** Dropped support for Node.js 18 and 20. Node.js 22 or greater is now
* **Breaking** Dropped commonjs support. The package is now only available as an ES module.
* **Breaking** Errors from the `WebServiceClient` are now thrown as
`WebServiceError` instances, which extend `Error`, rather than as plain
objects. The `code`, `error`, `status`, and `url` properties are preserved,
so existing field access continues to work, but the thrown value is now an
`Error`. The original error is now preserved as the standard `cause`
property (for example, the network error behind a `FETCH_ERROR`). The
`WebServiceError` class and the `WebServiceClientError` type are now exported
from the package.

6.3.4 (2025-11-25)
------------------
Expand Down
18 changes: 14 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ If the request succeeds, the function's Promise will resolve with the model
for the end point you called. This model in turn contains multiple
records, each of which represents part of the data returned by the web service.

If the request fails, the function's Promise will reject with an error object.
If the request fails, the function's Promise will reject with a
`WebServiceError` (see [Web Service Errors](#web-service-errors) below).

See the [API documentation](https://maxmind.github.io/GeoIP2-node/) for
more details.
Expand Down Expand Up @@ -106,25 +107,34 @@ client.insights('142.1.1.1').then(response => {
For details on the possible errors returned by the web service itself, [see
the GeoIP web service documentation](https://dev.maxmind.com/geoip/docs/web-services/responses/#errors).

If the web service returns an explicit error document, the promise will be rejected
with the following object structure:
Failures reject with a `WebServiceError`, which extends the built-in `Error`.
It exposes the following properties:

```js
{
code: 'THE_ERROR_CODE',
error: 'some human readable error',
status: 400, // the HTTP status code, when available
url: 'https://geoip.maxmind.com...',
cause: <the underlying error, when one exists>,
}
```

`error` is also available as the standard `Error` `message`, and when the
failure was caused by another error (for example, a network failure), the
original error is available as `cause`. Both `WebServiceError` and the
`WebServiceClientError` type are exported from the package.

In addition to the possible errors returned by the web service, the following error
codes are provided:

* `SERVER_ERROR` for 5xx level errors
* `HTTP_STATUS_CODE_ERROR` for unexpected HTTP status codes
* `INVALID_RESPONSE_BODY` for invalid JSON responses or unparseable response bodies
* `NETWORK_TIMEOUT` for network request timeouts
* `FETCH_ERROR` for internal `fetch` errors
* `FETCH_ERROR` for internal `fetch` errors. The `error` message includes the
underlying failure reason (e.g. a DNS or connection error) when available,
and the original error is attached as `cause`.

## Database Usage

Expand Down
95 changes: 95 additions & 0 deletions src/errors.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { WebServiceError } from './errors.js';

describe('WebServiceError', () => {
it('is an Error instance', () => {
const err = new WebServiceError({
code: 'FETCH_ERROR',
error: 'something went wrong',
url: 'https://example.com',
});

expect(err).toBeInstanceOf(Error);
expect(err).toBeInstanceOf(WebServiceError);
expect(err.name).toBe('WebServiceError');
});

it('exposes code, error, status, and url', () => {
const err = new WebServiceError({
code: 'SERVER_ERROR',
error: 'boom',
status: 500,
url: 'https://example.com',
});

expect(err.code).toBe('SERVER_ERROR');
expect(err.error).toBe('boom');
expect(err.status).toBe(500);
expect(err.url).toBe('https://example.com');
});

it('uses the error string as the message', () => {
const err = new WebServiceError({
code: 'FETCH_ERROR',
error: 'the message',
url: 'https://example.com',
});

expect(err.message).toBe('the message');
expect(err.error).toBe(err.message);
});

it('preserves the underlying cause', () => {
const cause = new TypeError('fetch failed');
const err = new WebServiceError(
{
code: 'FETCH_ERROR',
error: 'TypeError - fetch failed',
url: 'https://example.com',
},
{ cause }
);

expect(err.cause).toBe(cause);
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

it('leaves cause undefined when not provided', () => {
const err = new WebServiceError({
code: 'FETCH_ERROR',
error: 'something went wrong',
url: 'https://example.com',
});

expect(err.cause).toBeUndefined();
expect(JSON.parse(JSON.stringify(err))).not.toHaveProperty('cause');
});

it('omits status when not provided', () => {
const err = new WebServiceError({
code: 'FETCH_ERROR',
error: 'something went wrong',
url: 'https://example.com',
});

expect(err.status).toBeUndefined();
expect(Object.prototype.hasOwnProperty.call(err, 'status')).toBe(false);
});

it('retains code, error, status, and url as enumerable properties', () => {
const err = new WebServiceError({
code: 'SERVER_ERROR',
error: 'boom',
status: 500,
url: 'https://example.com',
});

const serialized = JSON.parse(JSON.stringify(err));
expect(serialized).toMatchObject({
code: 'SERVER_ERROR',
error: 'boom',
status: 500,
url: 'https://example.com',
});
// `name` lives on the prototype, so it is not serialized.
expect(serialized).not.toHaveProperty('name');
});
});
61 changes: 61 additions & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,66 @@
import { WebServiceClientError } from './types.js';

/* tslint:disable:max-classes-per-file */

/**
* An error returned by the GeoIP2 web service or encountered while
* communicating with it.
*
* In addition to the standard `Error` properties (including `cause`, which
* holds the underlying error when one exists, such as the network error
* behind a `FETCH_ERROR`), it exposes the `code`, `status`, and `url`
* associated with the failure.
*/
export class WebServiceError extends Error implements WebServiceClientError {
/**
* The error code returned by the web service or generated by this client.
*/
public readonly code: string;
/**
* A human-readable description of the error. This is an alias of `message`,
* retained for backward compatibility.
*/
public readonly error: string;
/**
* The HTTP status code, when the error originated from an HTTP response.
*
* Declared with `declare` so that no class field is emitted: the property is
* absent (rather than set to `undefined`) when no status applies, e.g. on
* network-level errors such as `FETCH_ERROR` and `NETWORK_TIMEOUT`.
*/
declare public readonly status?: number;
/**
* The URL that was being requested when the error occurred.
*/
public readonly url: string;

constructor(
properties: {
code: string;
error: string;
status?: number;
url: string;
},
options?: { cause?: unknown }
) {
super(properties.error, options);
this.code = properties.code;
this.error = properties.error;
// Only assign `status` when present so it stays genuinely optional: on
// network-level errors (e.g. FETCH_ERROR, NETWORK_TIMEOUT) the instance
// carries no `status` property at all, rather than `status: undefined`.
if (properties.status !== undefined) {
this.status = properties.status;
}
this.url = properties.url;
}
}

// Set `name` on the prototype rather than in the constructor. Using a string
// literal keeps the name correct under minification, and keeping it off the
// instance means it stays out of `JSON.stringify` output.
WebServiceError.prototype.name = 'WebServiceError';
Comment on lines +59 to +62

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
node <<'NODE'
class AssignedNameError extends Error {}
AssignedNameError.prototype.name = 'AssignedNameError';

class DefinedNameError extends Error {}
Object.defineProperty(DefinedNameError.prototype, 'name', {
  value: 'DefinedNameError',
  writable: true,
  configurable: true,
});

console.log('Error.prototype.name:', Object.getOwnPropertyDescriptor(Error.prototype, 'name'));
console.log('AssignedNameError.prototype.name:', Object.getOwnPropertyDescriptor(AssignedNameError.prototype, 'name'));
console.log('DefinedNameError.prototype.name:', Object.getOwnPropertyDescriptor(DefinedNameError.prototype, 'name'));
NODE

Repository: maxmind/GeoIP2-node

Length of output: 514


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the relevant file section with line numbers.
sed -n '1,140p' src/errors.ts | cat -n

Repository: maxmind/GeoIP2-node

Length of output: 3515


Make WebServiceError.prototype.name non-enumerable

Direct assignment makes name enumerable on the prototype, so for...in on instances will surface it unlike built-in Error. Use Object.defineProperty here instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/errors.ts` around lines 50 - 53, The WebServiceError prototype name
assignment makes name enumerable, unlike built-in Error behavior. Update the
WebServiceError prototype setup in src/errors.ts to use Object.defineProperty on
WebServiceError.prototype so name stays non-enumerable while still preserving
the literal class name for minification safety. Keep the change scoped to the
WebServiceError prototype initialization.


/**
* This error is thrown when the IP address is not found in the database.
* This generally means that the address was a private or reserved address.
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ export { Reader, ReaderModel, WebServiceClient };
export * from './records.js';
export * from './models/index.js';
export * from './errors.js';
export type { WebServiceClientError } from './types.js';
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ export interface WebServiceClientError {
error: string;
status?: number;
url: string;
/**
* The underlying error that caused this one, when available (for example,
* the network error behind a `FETCH_ERROR`).
*/
cause?: unknown;
}

export interface Json {
Expand Down
Loading