better error handling (thanks Joseph Liu)