I am currently working on a web application as a learning project, which has a NodeJS backend and uses a MongoDB database; however, I believe my question is not specific to the technologies I am using.
When creating a RESTful API, I can appreciate that you should always respond to the client with the appropriate HTTP error code whenever your program encounters an error during execution (i.e. respond with some HTTP error code when MongoDB encounters an issue trying to fetch some data and provide some front end feedback about error). For example, you would typically do the following when creating an entry in a MongoDB database
Model.create({
// create some data in my db
}, (err, data) => {
if (err) {
// respond with 404
} else {
// respond with 200 and serve data to client
}
})
However, I'm unsure as to how I should handle errors in instances outside of the above. For example, for code that executes on a regular interval that is not requested by a client, what should I do with the error given that I would expect this routine code to run smoothly all the time?
Is the standard engineering practice to have an alert sent to me when an error is thrown? My current solution is to simply console.log the error which seems completely pointless since I wouldn't be watching my server 24/7 so any logged errors would go unnoticed.
Model.create({
// create some data in my db
}, (err, data) => {
if (err) {
// what should I do here??
// currently pointlessly console.logging here...
} else {
// do something on success
}
})
Below is another instance where I'm unsure of how I should handle error. Here, I'm sending a slack notification every time something happens to monitor my application and I would expect this to work every time. If a message fails to send, it's no big deal but what do I do with the error?
slack.webhook({ // posts message to slack
channel: "#general",
username: "bot",
text: `Yay success`
}, function(err, response) {
// what should I do if the slack message doesn't send??
// Send an alert to tell me that there is an issue with sending messages to slack?
// Force the app to keep trying to resend a message until it's successful?
});