Cleanup diagnostics and error handling along with tests for it.