Skip to content

Commit

Permalink
Handle error response bodies
Browse files Browse the repository at this point in the history
  • Loading branch information
ptpaterson committed Mar 8, 2024
1 parent 06a4e17 commit 3258c1c
Showing 1 changed file with 33 additions and 31 deletions.
64 changes: 33 additions & 31 deletions src/http-client/node-http2-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,42 +247,44 @@ export class NodeHTTP2Client implements HTTPClient, HTTPStreamClient {
http2ResponseHeaders[http2.constants.HTTP2_HEADER_STATUS]
);
if (!(status >= 200 && status < 400)) {
// TODO: if we get bad status, then we should still finish reading the response, and create
// the appropriate error instance
rejectChunk(
new ServiceError(
{
error: {
code: "fauna error",
message: "fauna error",
},
},
status
)
);
}
// Get the error body and then throw an error
let responseData = "";

// append response data to the data string every time we receive new
// data chunks in the response
req.on("data", (chunk: string) => {
responseData += chunk;
});

let partOfLine = "";
// Once the response is finished, resolve the promise
// TODO: The Client contains the information for how to parse an error
// into the appropriate class, so lift this logic out of the HTTPClient.
req.on("end", () => {
rejectChunk(new ServiceError(JSON.parse(responseData), status));
});
} else {
let partOfLine = "";

// append response data to the data string every time we receive new
// data chunks in the response
req.on("data", (chunk: string) => {
const chunkLines = (partOfLine + chunk).split("\n");
// append response data to the data string every time we receive new
// data chunks in the response
req.on("data", (chunk: string) => {
const chunkLines = (partOfLine + chunk).split("\n");

// Yield all complete lines
for (let i = 0; i < chunkLines.length - 1; i++) {
resolveChunk(chunkLines[i].trim());
chunkPromise = setChunkPromise();
}
// Yield all complete lines
for (let i = 0; i < chunkLines.length - 1; i++) {
resolveChunk(chunkLines[i].trim());
chunkPromise = setChunkPromise();
}

// Store the partial line
partOfLine = chunkLines[chunkLines.length - 1];
});
// Store the partial line
partOfLine = chunkLines[chunkLines.length - 1];
});

// Once the response is finished, resolve the promise
req.on("end", () => {
resolveChunk(partOfLine);
});
// Once the response is finished, resolve the promise
req.on("end", () => {
resolveChunk(partOfLine);
});
}
};

// eslint-disable-next-line @typescript-eslint/no-this-alias
Expand Down

0 comments on commit 3258c1c

Please sign in to comment.