Improved error handling for mangle function