error handling and inserting debug messages