Fix error handling when connecting to database