Improve error detection and logging