Improved error handling

Improved error handling #170
(sorry, no idea how to do pull requests properly)