Extract error code from error message or parsed error dict. Returns error code if matched, None otherwise.
(reason: str, parsed_error: Optional[Dict] = None)
| 191 | |
| 192 | |
| 193 | def extract_error_code(reason: str, parsed_error: Optional[Dict] = None) -> Optional[str]: |
| 194 | """ |
| 195 | Extract error code from error message or parsed error dict. |
| 196 | Returns error code if matched, None otherwise. |
| 197 | """ |
| 198 | # 1) parsed_error dict |
| 199 | if parsed_error and isinstance(parsed_error, dict): |
| 200 | code = parsed_error.get("error_code") |
| 201 | if code: |
| 202 | return code |
| 203 | |
| 204 | # 2) try parse reason as JSON |
| 205 | try: |
| 206 | parsed = json.loads(reason) |
| 207 | if isinstance(parsed, dict): |
| 208 | code = parsed.get("error_code") |
| 209 | if code: |
| 210 | return code |
| 211 | detail = parsed.get("detail") |
| 212 | if isinstance(detail, dict) and detail.get("error_code"): |
| 213 | return detail.get("error_code") |
| 214 | except Exception: |
| 215 | pass |
| 216 | |
| 217 | # 3) regex from raw string (supports single/double quotes) |
| 218 | try: |
| 219 | match = re.search( |
| 220 | r'["\']error_code["\']\s*:\s*["\']([^"\']+)["\']', reason) |
| 221 | if match: |
| 222 | return match.group(1) |
| 223 | except Exception: |
| 224 | pass |
| 225 | |
| 226 | return "unknown_error" |
| 227 | |
| 228 | |
| 229 | def save_error_to_redis(task_id: str, error_reason: str, start_time: float): |