improved error handling logic