Pārlūkot izejas kodu

Add error handling

Check if service can initialize data source before making requests.
master
TheoryOfNekomata pirms 8 mēnešiem
vecāks
revīzija
284a5cd3bf
1 mainītis faili ar 35 papildinājumiem un 22 dzēšanām
  1. +35
    -22
      src/handlers.ts

+ 35
- 22
src/handlers.ts Parādīt failu

@@ -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;


Notiek ielāde…
Atcelt
Saglabāt