Files
awesome-copilot/cookbook/copilot-sdk/python/error-handling.md
James Montemagno 33f544c71d Align Copilot SDK documentation with permission handling requirements (#1107)
* Apply permission handler requirements across Copilot SDK docs

Co-authored-by: jamesmontemagno <1676321+jamesmontemagno@users.noreply.github.com>
Agent-Logs-Url: https://github.com/jamesmontemagno/awesome-copilot/sessions/adf27a88-92f8-4ca6-b3fe-1204e3bb9963

* Polish permission update formatting in SDK examples

Co-authored-by: jamesmontemagno <1676321+jamesmontemagno@users.noreply.github.com>
Agent-Logs-Url: https://github.com/jamesmontemagno/awesome-copilot/sessions/adf27a88-92f8-4ca6-b3fe-1204e3bb9963

* Fix review comments on SDK permission handling PR

Address 5 review comments from PR #1103:

1. Fix invalid object literal syntax (stray comma) in resumeSession
   example in copilot-sdk-nodejs.instructions.md

2. Replace unused PermissionHandler import with actual usage in
   cookbook/copilot-sdk/python/recipe/ralph_loop.py (was using
   inline lambda instead)

3. Replace unused approveAll import with actual usage in
   cookbook/copilot-sdk/nodejs/recipe/ralph-loop.ts (was using
   inline handler instead)

4. Add missing PermissionHandler import to 4 Python code snippets
   in skills/copilot-sdk/SKILL.md that reference it without importing

5. Add missing approveAll import to 3 TypeScript code snippets
   in skills/copilot-sdk/SKILL.md that reference it without importing

* Refactor session creation to improve code formatting and consistency across SDK examples

* Fix formatting: split multi-property lines and put closing braces on own lines

Address review comments on PR #1107:
- Split OnPermissionRequest + Model onto separate lines in Go, C#, TypeScript
- Put closing }); on its own line consistently across all examples
- Fix indentation in SKILL.md Quick Start, CLI URL, Error Handling sections
- Fix cookbook Go multiple-sessions and error-handling formatting
- Fix ralph-loop.md TypeScript indentation

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: jamesmontemagno <1676321+jamesmontemagno@users.noreply.github.com>
2026-03-23 11:11:19 +11:00

2.8 KiB

Error Handling Patterns

Handle errors gracefully in your Copilot SDK applications.

Runnable example: recipe/error_handling.py

cd recipe && pip install -r requirements.txt
python error_handling.py

Example scenario

You need to handle various error conditions like connection failures, timeouts, and invalid responses.

Basic try-except

import asyncio
from copilot import CopilotClient, SessionConfig, MessageOptions, PermissionHandler

async def main():
    client = CopilotClient()

    try:
        await client.start()
        session = await client.create_session(SessionConfig(model="gpt-5",
        on_permission_request=PermissionHandler.approve_all))

        response = await session.send_and_wait(MessageOptions(prompt="Hello!"))

        if response:
            print(response.data.content)

        await session.destroy()
    except Exception as e:
        print(f"Error: {e}")
    finally:
        await client.stop()

if __name__ == "__main__":
    asyncio.run(main())

Handling specific error types

try:
    await client.start()
except FileNotFoundError:
    print("Copilot CLI not found. Please install it first.")
except ConnectionError:
    print("Could not connect to Copilot CLI server.")
except Exception as e:
    print(f"Unexpected error: {e}")

Timeout handling

session = await client.create_session(SessionConfig(model="gpt-5",
        on_permission_request=PermissionHandler.approve_all))

try:
    # send_and_wait accepts an optional timeout in seconds
    response = await session.send_and_wait(
        MessageOptions(prompt="Complex question..."),
        timeout=30.0
    )
    print("Response received")
except TimeoutError:
    print("Request timed out")

Aborting a request

session = await client.create_session(SessionConfig(model="gpt-5",
        on_permission_request=PermissionHandler.approve_all))

# Start a request (non-blocking send)
await session.send(MessageOptions(prompt="Write a very long story..."))

# Abort it after some condition
await asyncio.sleep(5)
await session.abort()
print("Request aborted")

Graceful shutdown

import signal
import sys

def signal_handler(sig, frame):
    print("\nShutting down...")
    try:
        loop = asyncio.get_running_loop()
        loop.create_task(client.stop())
    except RuntimeError:
        asyncio.run(client.stop())
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

Best practices

  1. Always clean up: Use try-finally to ensure await client.stop() is called
  2. Handle connection errors: The CLI might not be installed or running
  3. Set appropriate timeouts: Use the timeout parameter on send_and_wait()
  4. Log errors: Capture error details for debugging