From 284a5cd3bfc710a812a68aa64b9b0d0000ac9a8d Mon Sep 17 00:00:00 2001 From: TheoryOfNekomata Date: Wed, 13 Mar 2024 14:39:42 +0800 Subject: [PATCH] Add error handling Check if service can initialize data source before making requests. --- src/handlers.ts | 57 ++++++++++++++++++++++++++++++------------------- 1 file changed, 35 insertions(+), 22 deletions(-) diff --git a/src/handlers.ts b/src/handlers.ts index 00e8281..b9ca157 100644 --- a/src/handlers.ts +++ b/src/handlers.ts @@ -138,15 +138,20 @@ export const handleGetCollection: Middleware = ({ }; } - await theResource.dataSource.initialize(); - const resData = await theResource.dataSource.getMultiple(); // TODO paginated responses per resource - const theFormatted = theSerializerPair.serialize(resData); + try { + await theResource.dataSource.initialize(); + const resData = await theResource.dataSource.getMultiple(); // TODO paginated responses per resource + const theFormatted = theSerializerPair.serialize(resData); - res.writeHead(constants.HTTP_STATUS_OK, { - 'Content-Type': theMediaType, - 'X-Resource-Total-Item-Count': resData.length - }); - res.end(theFormatted); + res.writeHead(constants.HTTP_STATUS_OK, { + 'Content-Type': theMediaType, + 'X-Resource-Total-Item-Count': resData.length + }); + res.end(theFormatted); + } catch { + res.statusCode = constants.HTTP_STATUS_INTERNAL_SERVER_ERROR; + res.end(); + } return { handled: true @@ -201,23 +206,31 @@ export const handleGetItem: Middleware = ({ }; } - await theResource.dataSource.initialize(); - const singleResDatum = await theResource.dataSource.getSingle(mainResourceId); - if (singleResDatum) { - const theFormatted = theSerializerPair.serialize(singleResDatum); - res.writeHead(constants.HTTP_STATUS_OK, { 'Content-Type': theMediaType }); - res.end(theFormatted); + try { + await theResource.dataSource.initialize(); + const singleResDatum = await theResource.dataSource.getSingle(mainResourceId); + if (singleResDatum) { + const theFormatted = theSerializerPair.serialize(singleResDatum); + res.writeHead(constants.HTTP_STATUS_OK, {'Content-Type': theMediaType}); + res.end(theFormatted); + return { + handled: true + }; + } + + res.statusCode = constants.HTTP_STATUS_NOT_FOUND; + res.statusMessage = `${theResource.itemName} Not Found`; + res.end(); + return { + handled: true + }; + } catch { + res.statusCode = constants.HTTP_STATUS_INTERNAL_SERVER_ERROR; + res.end(); return { handled: true }; } - - res.statusCode = constants.HTTP_STATUS_NOT_FOUND; - res.statusMessage = `${theResource.itemName} Not Found`; - res.end(); - return { - handled: true - }; }; @@ -271,8 +284,8 @@ export const handleDeleteItem: Middleware = ({ } } - await theResource.dataSource.initialize(); try { + await theResource.dataSource.initialize(); const response = await theResource.dataSource.delete(mainResourceId); if (typeof response !== 'undefined' && !response && theResource.throws404OnDeletingNotFound) { res.statusCode = constants.HTTP_STATUS_NOT_FOUND;