Refactored the error handling because it's going to be used by multiple functions now.