Large error handling refactor, to make for better testability