refactor error handling, fixes #3070, #3171