Skip to content

Commit

Permalink
Improve error handling in event.route.js
Browse files Browse the repository at this point in the history
  • Loading branch information
leungkinghin-ct committed Aug 16, 2023
1 parent c71e59f commit 6cf1518
Showing 1 changed file with 22 additions and 14 deletions.
36 changes: 22 additions & 14 deletions incremental-updater/src/routes/event.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,27 @@ import { logger } from '../utils/logger.utils.js';
const eventRouter = Router();

async function eventHandler(request, response) {
// Check request body
if (!request.body) {
logger.error('Missing request body.');
throw new CustomError(400, 'Bad request: No Pub/Sub message was received');
}
try {
// Check request body
if (!request.body) {
logger.error('Missing request body.');
throw new CustomError(
400,
'Bad request: No Pub/Sub message was received'
);
}

// Check if the body comes in a message
if (!request.body.message) {
logger.error('Missing body message');
throw new CustomError(400, 'Bad request: Wrong No Pub/Sub message format');
}
// Check if the body comes in a message
if (!request.body.message || !request.body.message.data) {
logger.error('Missing message data in incoming message');
throw new CustomError(
400,
'Bad request: No message data in incoming message'
);
}

const encodedMessageBody = request.body.message.data;

const encodedMessageBody = request.body?.message?.data;
if (encodedMessageBody) {
const buff = new Buffer(encodedMessageBody, 'base64');
const messageBody = JSON.parse(buff.toString('ascii'));

Expand All @@ -44,8 +51,9 @@ async function eventHandler(request, response) {
'Bad request: Resource type is not defined in incoming message data'
);
}
} else {
throw new CustomError(400, 'Bad request: message data is not defined');
} catch (err) {
logger.error(err);
return response.status(err.statusCode).send(err);
}
}

Expand Down

0 comments on commit 6cf1518

Please sign in to comment.