Better error handling. Fixes #1774