Fixed error handling

Made error handling more efficient