Skip to content

Commit

Permalink
Improve error handling in usage service and return correct HTTP code (
Browse files Browse the repository at this point in the history
  • Loading branch information
TuvalSimha authored Nov 28, 2024
1 parent e33276a commit e48eb6d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 16 deletions.
4 changes: 4 additions & 0 deletions packages/services/service-common/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,7 @@ export function invariant(
const value: string = provided ? `${prefix}: ${provided}` : prefix;
throw new Error(value);
}

export function maskToken(token: string) {
return token.substring(0, 3) + '*'.repeat(token.length - 6) + token.substring(token.length - 3);
}
36 changes: 20 additions & 16 deletions packages/services/service-common/src/sentry.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,46 @@
import type { FastifyInstance, FastifyPluginAsync } from 'fastify';
import fp from 'fastify-plugin';
import * as Sentry from '@sentry/node';
import { cleanRequestId } from './helpers';
import { cleanRequestId, maskToken } from './helpers';

const plugin: FastifyPluginAsync = async server => {
server.decorateReply('sentry', null);

server.setErrorHandler((err, req, reply) => {
Sentry.withScope(scope => {
scope.setUser({
ip_address: req.ip,
});

scope.setUser({ ip_address: req.ip });
const requestId = cleanRequestId(req.headers['x-request-id']);

const tokenHeader = req.headers['x-api-token'] || req.headers.authorization;
const maskedToken = typeof tokenHeader === 'string' ? maskToken(tokenHeader) : null;
if (requestId) {
scope.setTag('request_id', requestId);
}

const { referer } = req.headers;

if (referer) {
scope.setTag('referer', referer);
}

scope.setTag('path', req.raw.url);
scope.setTag('method', req.raw.method);
if (maskedToken) {
scope.setTag('masked_token', maskedToken);
}
req.log.error(err);
Sentry.captureException(err);

req.log.warn('Replying with 500 Internal Server Error');
if (err.code === 'FST_ERR_CRT_BODY_TOO_LARGE') {
req.log.warn('Payload too large');
void reply.status(413).send({
error: 413,
message: 'Payload Too Large',
});
return;
}

void reply.status(500).send(
JSON.stringify({
error: 500,
message: 'Internal Server Error',
}),
);
req.log.warn('Replying with 500 Internal Server Error');
void reply.status(500).send({
error: 500,
message: 'Internal Server Error',
});
});
});
};
Expand Down

0 comments on commit e48eb6d

Please sign in to comment.