Skip to content

Commit

Permalink
Translate encoder error codes to strings
Browse files Browse the repository at this point in the history
When decoding, we use raise_oserror() to convert codec error codes to
strings.  Adapt that code to be used when encoding as well.  Add a new
helper function that returns the exception so we can still raise
`from exc`.

Ideally we'd replace the other two callers of raise_oserror() with
`raise _get_oserror()`, but the former is part of the public API.
  • Loading branch information
bgilbert committed Dec 4, 2023
1 parent c2fe53c commit ff34e1b
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/PIL/ImageFile.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,19 @@
# Helpers


def raise_oserror(error):
def _get_oserror(error, encoder=False):

Check warning on line 64 in src/PIL/ImageFile.py

View check run for this annotation

Codecov / codecov/patch

src/PIL/ImageFile.py#L64

Added line #L64 was not covered by tests
try:
msg = Image.core.getcodecstatus(error)
except AttributeError:
msg = ERRORS.get(error)
if not msg:
msg = f"decoder error {error}"
msg += " when reading image file"
raise OSError(msg)
msg = f"{'encoder' if encoder else 'decoder'} error {error}"
msg += f" when {'writing' if encoder else 'reading'} image file"
return OSError(msg)

Check warning on line 72 in src/PIL/ImageFile.py

View check run for this annotation

Codecov / codecov/patch

src/PIL/ImageFile.py#L70-L72

Added lines #L70 - L72 were not covered by tests


def raise_oserror(error):
raise _get_oserror(error)

Check warning on line 76 in src/PIL/ImageFile.py

View check run for this annotation

Codecov / codecov/patch

src/PIL/ImageFile.py#L75-L76

Added lines #L75 - L76 were not covered by tests


def _tilesort(t):
Expand Down Expand Up @@ -542,8 +546,7 @@ def _encode_tile(im, fp, tile, bufsize, fh, exc=None):
# slight speedup: compress to real file object
errcode = encoder.encode_to_file(fh, bufsize)
if errcode < 0:
msg = f"encoder error {errcode} when writing image file"
raise OSError(msg) from exc
raise _get_oserror(errcode, encoder=True) from exc

Check warning on line 549 in src/PIL/ImageFile.py

View check run for this annotation

Codecov / codecov/patch

src/PIL/ImageFile.py#L549

Added line #L549 was not covered by tests
finally:
encoder.cleanup()

Expand Down

0 comments on commit ff34e1b

Please sign in to comment.