if you have an error, connection is undefined.

When you have a connection err, connection is undefined.  So calling connection.err() results in a stack dump.  

I simply checked to see if connection was there before calling .err().