Learn
Learn Node SQLite
Handling Errors Gracefully

No one’s perfect. Code, like people, can make mistakes. This is OK! What’s important is that we learn how to handle our difficulties while keeping our composure. Handling errors is an important part of the process when dealing with Node & SQL in particular. When our code throws an error, we should be able to handle it before it reaches our end users and incites panic and concern. We still want to know what happened, so that we can perform a suitable action based on the error that occurred — so we catch the error.

For db.run(), db.each(), db.get(), and db.all(), the first argument to the callback will always be an Error object if an error occurred. If there is no error, this argument will be null. We can check if this error exists, and if it does exist, we can handle it.

Instructions

1.

Add an if check to see if an error exists in the callback of the INSERT statement in db.run(). The error will be null if no error exists. Log an error if one is passed into the callback and return to break out of the callback;

2.

You can see the SQLite error in the console: we are missing a value for the temp_avg column, whoops! It turns out that the average temperature in Istanbul in 1976 was 13.35. Fix your INSERT statement to add it to the TemperatureData table. Make sure to leave your log for this.lastID in the db.run() callback.

3.

Now that the ID is being logged, open a db.get() query that SELECTs the inserted row by id. You should use a placeholder to interpolate this.lastID into your SELECT statement.

In a callback to that db.get() query, log the row again to show that it’s been entered into our database using printQueryResults

Folder Icon

Sign up to start coding

Already have an account?