Error handling refactoring

TODO