|
| 1 | +from .. import error |
| 2 | + |
| 3 | +__all__ = ["SDLError", "raise_sdl_err"] |
| 4 | + |
| 5 | + |
| 6 | +class SDLError(Exception): |
| 7 | + """A custom exception class for SDL2-specific errors. |
| 8 | + |
| 9 | + Args: |
| 10 | + msg (str, optional): The error message for the exception. If not |
| 11 | + provided, the current SDL error (if any) will be retrieved using |
| 12 | + `:func:~sdl2.SDL_GetError`. |
| 13 | + """ |
| 14 | + |
| 15 | + def __init__(self, msg=None): |
| 16 | + super(SDLError, self).__init__() |
| 17 | + self.msg = msg |
| 18 | + if not msg: |
| 19 | + self.msg = error.SDL_GetError() |
| 20 | + error.SDL_ClearError() |
| 21 | + |
| 22 | + def __str__(self): |
| 23 | + return repr(self.msg) |
| 24 | + |
| 25 | + |
| 26 | +def raise_sdl_err(desc=None): |
| 27 | + """Raises an exception for an internal SDL error. |
| 28 | + |
| 29 | + The format of the exception message depends on whether a description is |
| 30 | + provided and whether `:func:~sdl2.SDL_GetError` returns an error string. |
| 31 | + If a description is given, it will be appended after the default text |
| 32 | + ``Error encountered``. If SDL has set an error string, it will be appended |
| 33 | + to the end of the message following a colon (clearing the error in the |
| 34 | + process). |
| 35 | + |
| 36 | + For example, if ``SDL_GetError() == b"unsupported pixel format"`` and the |
| 37 | + function is called as ``raise_sdl_err("creating the surface")``, the |
| 38 | + resulting exception message will be "Error encountered creating the surface: |
| 39 | + unsupported pixel format". |
| 40 | +
|
| 41 | + Args: |
| 42 | + desc (str. optional): A description of what SDL was trying to do when |
| 43 | + the error occurred. Will be placed after the text "Error encountered" |
| 44 | + in the exception message if provided. |
| 45 | +
|
| 46 | + Raises: |
| 47 | + :exc:`~SDLError`: An exception explaining the most recent SDL error. |
| 48 | +
|
| 49 | + """ |
| 50 | + errmsg = error.SDL_GetError().decode('utf-8') |
| 51 | + error.SDL_ClearError() |
| 52 | + e = "Error encountered" |
| 53 | + if desc: |
| 54 | + e += " " + desc |
| 55 | + if len(errmsg): |
| 56 | + e += ": {0}".format(errmsg) |
| 57 | + raise SDLError(e) |
0 commit comments