Skip to content

Commit

Permalink
fix: removing custom error
Browse files Browse the repository at this point in the history
  • Loading branch information
leftieFriele committed Nov 1, 2024
1 parent 1aab57c commit f071157
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 44 deletions.
4 changes: 0 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,6 @@ For a complete list of options, consult the [undici documentation](https://undic

Closes the client and it's connections.

## HttpClientError

Errors thrown from the library will be of the class `HttpClientError`

[@metrics/metric]: https://github.com/metrics-js/metric '@metrics/metric'
[abslog]: https://github.com/trygve-lie/abslog 'abslog'
[undici]: https://undici.nodejs.org/
Expand Down
8 changes: 3 additions & 5 deletions examples/failing.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import HttpClient, { HttpClientError } from '../lib/http-client.js';
import HttpClient from '../lib/http-client.js';

/**
* Example of the circuit breaker opening on a failing request.
Expand All @@ -22,9 +22,7 @@ try {
method: 'GET',
});
} catch (err) {
if (err instanceof HttpClientError) {
if (err.code === HttpClientError.ServerDown) {
console.error('Server unavailable..');
}
if (err.toString() === 'Error: Breaker is open') {
console.error('Server unavailable..');
}
}
57 changes: 27 additions & 30 deletions lib/http-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export default class HttpClient {
#agent;
#breaker;
#followRedirects;
// eslint-disable-next-line no-unused-private-class-members
#hasFallback = false;
#logger;
#throwOn400;
Expand Down Expand Up @@ -84,7 +85,7 @@ export default class HttpClient {
}

async #request(options = {}) {
if (this.#followRedirects) {
if (this.#followRedirects || options.redirectable) {
const { redirect } = interceptors;
options.dispatcher = this.#agent.compose(
redirect({ maxRedirections: 1 }),
Expand All @@ -97,7 +98,13 @@ export default class HttpClient {
...options,
});

if (this.#throwOn400 && statusCode >= 400 && statusCode <= 499) {
// TODO Look into this, as the resovlers have their own handling of this
// In order to be backward compatible, both throw options must be false
if (
(this.#throwOn400 || options.throwable) &&
statusCode >= 400 &&
statusCode <= 499
) {
// Body must be consumed; https://github.com/nodejs/undici/issues/583#issuecomment-855384858
const errBody = await body.text();
this.#logger.trace(
Expand All @@ -106,9 +113,12 @@ export default class HttpClient {
throw createError(statusCode);
}

if (this.#throwOn500 && statusCode >= 500 && statusCode <= 599) {
if (
(this.#throwOn500 || options.throwable) &&
statusCode >= 500 &&
statusCode <= 599
) {
// Body must be consumed; https://github.com/nodejs/undici/issues/583#issuecomment-855384858
await body.text();
const errBody = await body.text();
this.#logger.trace(
`HTTP ${statusCode} error catched by client. Body: ${errBody}`,
Expand Down Expand Up @@ -138,20 +148,7 @@ export default class HttpClient {
* @returns {Promise<any>}
*/
async request(options = {}) {
try {
return await this.#breaker.fire(options);
} catch (error) {
if (!this.#hasFallback) {
throw new HttpClientError(
`Error on ${options.method} ${options.origin}${options.path}`,
{
code: error.code,
cause: error,
options,
},
);
}
}
return await this.#breaker.fire(options);
}

/**
Expand All @@ -169,15 +166,15 @@ export default class HttpClient {
/**
* Error class for the client
*/
export class HttpClientError extends Error {
// Not sure if there is a need for this tbh, but I threw it in there so we can see how it feels.
static ServerDown = 'EOPENBREAKER';

constructor(message, { code, cause, options }) {
super(message);
this.name = 'HttpClientError';
this.code = code;
this.cause = cause;
this.options = options;
}
}
// export class HttpClientError extends Error {
// // Not sure if there is a need for this tbh, but I threw it in there so we can see how it feels.
// static ServerDown = 'EOPENBREAKER';
//
// constructor(message, { code, cause, options }) {
// super(message);
// this.name = 'HttpClientError';
// this.code = code;
// this.cause = cause;
// this.options = options;
// }
// }
13 changes: 8 additions & 5 deletions tests/http-client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ async function queryUrl({
await client.request({ path, origin: url, method: 'GET' });
} catch (err) {
// Push the actual cause here for the tests
if (!suppressErrors) errors.push(err.cause);
if (!suppressErrors) errors.push(err);
}
}
if (errors.length > 0) {
throw new Error(errors.toString());
throw new Error(errors);

Check failure on line 47 in tests/http-client.test.js

View workflow job for this annotation

GitHub Actions / test

Argument of type 'any[]' is not assignable to parameter of type 'string'.
}
}
await test('http-client - basics', async (t) => {
Expand Down Expand Up @@ -90,8 +90,7 @@ await test('http-client - basics', async (t) => {
});
},
{
name: 'HttpClientError',
message: 'Error on GET https://does-not-exist.domain/',
name: 'Error',
},
);
await client.close();
Expand Down Expand Up @@ -210,7 +209,7 @@ await test('http-client - circuit breaker behaviour', async (t) => {
method: 'GET',
});
} catch (err) {
if (err.cause.code === 'EOPENBREAKER') {
if (err.toString() === 'Error: Breaker is open') {
broken++;
}
}
Expand All @@ -222,6 +221,7 @@ await test('http-client - circuit breaker behaviour', async (t) => {
);
await afterEach(client);
});

await t.test('can reset breaker', async () => {
beforeEach();
const invalidUrl = `http://${host}:3023`;
Expand Down Expand Up @@ -250,4 +250,7 @@ await test('http-client - circuit breaker behaviour', async (t) => {
assert.strictEqual(response.statusCode, 200);
await afterEach(client);
});
// await t.test('has a .metrics property', async () => {
// const client = new HttpClient({ threshold: 50, reset: breakerReset });
// });
});

0 comments on commit f071157

Please sign in to comment.