Error handling logic improved

@diego-garber please review and merge.