Attempt to improve error handling.
Added some error handling, not sure how well it will work yet though.