Modified error handling to avoid 'Headers already sent' message