Improved error handling.

Try to return a relevant error code if things don't work out.