Spaces:
Running
Running
| #error_handling.py | |
| import traceback | |
| import gradio as gr | |
| import requests | |
| import html | |
| def display_error(message, e=None): | |
| """Formats an error message for display in Gradio. Returns a gr.update object.""" | |
| error_prefix = "❌ Error: " | |
| full_message = f"{error_prefix}{message}" | |
| if e: | |
| tb = traceback.format_exc() | |
| print(f"--- ERROR ---") | |
| print(f"Message: {message}") | |
| print(f"Exception Type: {type(e)}") | |
| print(f"Exception: {e}") | |
| # Avoid printing traceback for simple Warnings like scope changes unless debugging deep | |
| if not isinstance(e, Warning): | |
| print(f"Traceback:\n{tb}") | |
| print(f"-------------") | |
| # Try to get more details from response if it's a requests error | |
| if isinstance(e, requests.exceptions.RequestException) and e.response is not None: | |
| try: | |
| error_details = e.response.json() | |
| details_str = json.dumps(error_details, indent=2) | |
| full_message += f"\nStatus Code: {e.response.status_code}\nDetails:\n```json\n{details_str}\n```" | |
| except json.JSONDecodeError: | |
| full_message += f"\nStatus Code: {e.response.status_code}\nResponse Text:\n```\n{e.response.text}\n```" | |
| elif hasattr(e, 'description'): # Handle OAuthLib errors which often have a description | |
| full_message += f"\nDetails: {getattr(e, 'description', str(e))}" | |
| else: | |
| # Display the specific warning/error message directly | |
| full_message += f"\nDetails: {str(e)}" | |
| else: | |
| print(f"Error: {message}") # Log simple message | |
| # Use Markdown for better formatting in Gradio output | |
| # Ensure it's wrapped in a way that Gradio Markdown understands as an error block if possible | |
| # Simple red text might be best cross-platform | |
| error_html = f"<p style='color: red; white-space: pre-wrap;'>{html.escape(full_message)}</p>" | |
| return gr.update(value=error_html, visible=True) |