Fixed error handling so that it is more universal