Skip to content

Commit

Permalink
fix(repeater): improve error handling (#144)
Browse files Browse the repository at this point in the history
fixes #142
  • Loading branch information
derevnjuk committed Jun 5, 2023
1 parent 3e5a08b commit 7dcf753
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,19 @@ describe('HttpRequestRunner', () => {
});
});

it('should handle timeout', async () => {
const { request, requestOptions } = createRequest();
nock(requestOptions.url).get('/').delayBody(2).reply(204);
const runner = setupRunner({ timeout: 1 });

const response = await runner.run(request);

expect(response).toMatchObject({
errorCode: 'Error',
message: 'This operation was aborted'
});
});

it('should handle non-HTTP errors', async () => {
const runner = setupRunner({}, new Logger(LogLevel.SILENT));
const { request } = createRequest();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,20 +89,14 @@ export class HttpRequestRunner implements RequestRunner {
}

private handleRequestError(err: any, options: Request): Response {
if (err.response) {
const { response } = err;
const { cause } = err;
const { message, code, syscall, name } = cause ?? err;
let errorCode = code ?? syscall ?? name;

return new Response({
protocol: this.protocol,
statusCode: response.statusCode,
headers: response.headers,
body: response.body
});
if (typeof errorCode !== 'string') {
errorCode = Error.name;
}

const message = err.cause?.message ?? err.message;
const errorCode = err.cause?.code ?? err.error?.syscall ?? err.name;

this.logger.error(
'Error executing request: "%s %s HTTP/1.1"',
options.method,
Expand All @@ -121,21 +115,22 @@ export class HttpRequestRunner implements RequestRunner {
const ac = new AbortController();
const { signal } = ac;
let timer: NodeJS.Timeout | undefined;
let res!: IncomingMessage;

try {
const req = this.createRequest(options, { signal });

timer = this.setTimeout(ac);
process.nextTick(() => req.end(options.body));

const [res]: [IncomingMessage] = (await once(req, 'response', {
[res] = (await once(req, 'response', {
signal
})) as [IncomingMessage];

return await this.truncateResponse(res);
} finally {
clearTimeout(timer);
}

return this.truncateResponse(res);
}

private createRequest(
Expand Down

0 comments on commit 7dcf753

Please sign in to comment.