import asyncio
from typing import Optional
from io import StringIO


def get_task_traceback(task: asyncio.Task) -> Optional[str]:
    """Get traceback for given task as string.
    Return traceback as string if exists. Or None if there was no error.
    """
    if task.exception() is None:
        return None
    with StringIO() as stream:
        task.print_stack(file=stream)
        stream.flush()
        stream.seek(0)
        return stream.read()