Improved code that checks the err variable with helper function