Node.js sqlite3 error handling

This post is an exercise in trying to learn how to debug errors in Node.js programs.

Trying to write some sqlite3 code in Node.js. MapBox has a lovely Node module, but the docs are a bit thin and assume Node expertise I do not yet have. This morning’s challenge is trying to gracefully handle an error if database.run(“DROP TABLE”) fails. All work is running after database.serialize, so no concurrency.

By default with no error handling code, an error will cause an Unhandled ‘error’ event that kills the process. But you can’t just catch an exception because this is Node.js and exceptions don’t really work. So instead you need to specify a callback to database.run(), to get the Error (or else inspect the results of a successful statement.) Fair enough.

But what is the Error object in the callback? The sqlite3 docs don’t document this anywhere. In Chrome I’d just console.log() the object and use the lovely inspector. Node’s equivalent to the inspector is util.inspect, and you want to set showHidden to 1 to really see it. And voila:

{ [Error: SQLITE_ERROR: no such table: logs]
  [stack]: [Getter/Setter],
  [arguments]: undefined,
  [type]: undefined,
  [message]: 'SQLITE_ERROR: no such table: logs',
  errno: 1,
  code: 'SQLITE_ERROR' }

So this object looks like an ordinary Error object, with the message property. In addition it has errno and code properties. And now I know.

Another way to have learned all this would be to use the Node debugger. It’s pretty primitive, but you can set breakpoints in your code with the “debugger;” statement or from the debugger command line with “sb(lineno)”. Once it breaks you want to run “repl” to switch to the scope of your running script, then you can inspect objects. It all works but is a bit awkward without a GUI. I miss Chrome’s beautiful debugger; should try out node-inspector or something similar.

The irony of all this is I don’t even need too handle this error; sqlite supports “DROP TABLE IF EXISTS”. But oh well, now I know more about sqlite3 error handling and how to debug Node programs.