Skip to content

Commit

Permalink
chore: adding error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
artursudnik committed Oct 17, 2023
1 parent a7e482b commit 1bec34c
Showing 1 changed file with 36 additions and 18 deletions.
54 changes: 36 additions & 18 deletions apps/vc-api/src/middlewares/http-logger.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,44 @@ export class HttpLoggerMiddleware implements NestMiddleware {

let finished = false;

const oldWrite = res.write;
const oldEnd = res.end;
const chunks: Buffer[] = [];
let responseBody: string;

res.write = (...args: unknown[]): boolean => {
chunks.push(args[0] as Buffer);
return oldWrite.apply(res, args);
};

res.end = (...args: unknown[]) => {
const chunk = args[0] as Buffer;

if (chunk) {
chunks.push(chunk);
}

responseBody = Buffer.concat(chunks).toString();
return oldEnd.apply(res, args);
};
try {
const oldWrite = res.write;
const oldEnd = res.end;
const chunks: Buffer[] = [];

res.write = (...args: unknown[]): boolean => {
try {
chunks.push(args[0] as Buffer);
} catch (err) {
this.logger.error(`error collecting response body chunk: ${err}`);
this.logger.verbose(err.stack);
}

return oldWrite.apply(res, args);
};

res.end = (...args: unknown[]) => {
try {
const chunk = args[0] as Buffer;

if (chunk) {
chunks.push(chunk);
}

responseBody = Buffer.concat(chunks).toString();
} catch (err) {
this.logger.error(`error collecting response body chunk: ${err}`);
this.logger.verbose(err.stack);
}

return oldEnd.apply(res, args);
};
} catch (err) {
this.logger.error(`error setting response body to be collected: ${err}`);
this.logger.verbose(err.stack);
}

res.on('finish', () => {
const message = `${res.statusCode} ${res.statusMessage} | ${req.ip} | [${method}] ${url} - ${
Expand Down

0 comments on commit 1bec34c

Please sign in to comment.