Better error handling

TODO: Review changes by @vinhhrv for potential merge into project.