Improve error handling and error messaging

Do we want to extract the pattern for clarity?