Fix bugs in the handling and reporting of unexpected errors