Further improve exception traceback readability

This commit is contained in:
Andrew Murray 2022-12-30 14:24:28 +11:00
parent 2ae55ccbda
commit 68fdd2a9e7
7 changed files with 35 additions and 31 deletions

View File

@ -201,9 +201,8 @@ class ImImageFile(ImageFile.ImageFile):
else:
raise SyntaxError(
"Syntax error in IM header: " + s.decode("ascii", "replace")
)
msg = "Syntax error in IM header: " + s.decode("ascii", "replace")
raise SyntaxError(msg)
if not n:
msg = "Not an IM file"

View File

@ -2129,7 +2129,7 @@ class Image:
Resampling.BOX,
Resampling.HAMMING,
):
message = f"Unknown resampling filter ({resample})."
msg = f"Unknown resampling filter ({resample})."
filters = [
f"{filter[1]} ({filter[0]})"
@ -2142,9 +2142,8 @@ class Image:
(Resampling.HAMMING, "Image.Resampling.HAMMING"),
)
]
raise ValueError(
message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
)
msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
raise ValueError(msg)
if reducing_gap is not None and reducing_gap < 1.0:
msg = "reducing_gap must be 1.0 or greater"
@ -2764,13 +2763,13 @@ class Image:
Resampling.BICUBIC,
):
if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS):
message = {
msg = {
Resampling.BOX: "Image.Resampling.BOX",
Resampling.HAMMING: "Image.Resampling.HAMMING",
Resampling.LANCZOS: "Image.Resampling.LANCZOS",
}[resample] + f" ({resample}) cannot be used."
else:
message = f"Unknown resampling filter ({resample})."
msg = f"Unknown resampling filter ({resample})."
filters = [
f"{filter[1]} ({filter[0]})"
@ -2780,9 +2779,8 @@ class Image:
(Resampling.BICUBIC, "Image.Resampling.BICUBIC"),
)
]
raise ValueError(
message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
)
msg += " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
raise ValueError(msg)
image.load()
@ -3077,7 +3075,8 @@ def fromarray(obj, mode=None):
try:
mode, rawmode = _fromarray_typemap[typekey]
except KeyError as e:
raise TypeError("Cannot handle this data type: %s, %s" % typekey) from e
msg = "Cannot handle this data type: %s, %s" % typekey
raise TypeError(msg) from e
else:
rawmode = mode
if mode in ["1", "L", "I", "P", "F"]:
@ -3276,9 +3275,8 @@ def open(fp, mode="r", formats=None):
fp.close()
for message in accept_warnings:
warnings.warn(message)
raise UnidentifiedImageError(
"cannot identify image file %r" % (filename if filename else fp)
)
msg = "cannot identify image file %r" % (filename if filename else fp)
raise UnidentifiedImageError(msg)
#

View File

@ -498,7 +498,8 @@ def buildTransform(
raise PyCMSError(msg)
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)
msg = "flags must be an integer between 0 and %s" + _MAX_FLAG
raise PyCMSError(msg)
try:
if not isinstance(inputProfile, ImageCmsProfile):
@ -601,7 +602,8 @@ def buildProofTransform(
raise PyCMSError(msg)
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)
msg = "flags must be an integer between 0 and %s" + _MAX_FLAG
raise PyCMSError(msg)
try:
if not isinstance(inputProfile, ImageCmsProfile):

View File

@ -63,12 +63,13 @@ Dict of known error codes returned from :meth:`.PyDecoder.decode`,
def raise_oserror(error):
try:
message = Image.core.getcodecstatus(error)
msg = Image.core.getcodecstatus(error)
except AttributeError:
message = ERRORS.get(error)
if not message:
message = f"decoder error {error}"
raise OSError(message + " when reading image file")
msg = ERRORS.get(error)
if not msg:
msg = f"decoder error {error}"
msg += " when reading image file"
raise OSError(msg)
def _tilesort(t):

View File

@ -146,7 +146,8 @@ class LutBuilder:
for p in self.patterns:
m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))
if not m:
raise Exception('Syntax error in pattern "' + p + '"')
msg = 'Syntax error in pattern "' + p + '"'
raise Exception(msg)
options = m.group(1)
pattern = m.group(2)
result = int(m.group(3))

View File

@ -817,10 +817,10 @@ class PdfParser:
try:
stream_len = int(result[b"Length"])
except (TypeError, KeyError, ValueError) as e:
raise PdfFormatError(
"bad or missing Length in stream dict (%r)"
% result.get(b"Length", None)
) from e
msg = "bad or missing Length in stream dict (%r)" % result.get(
b"Length", None
)
raise PdfFormatError(msg) from e
stream_data = data[m.end() : m.end() + stream_len]
m = cls.re_stream_end.match(data, m.end() + stream_len)
check_format_condition(m, "stream end not found")
@ -874,7 +874,8 @@ class PdfParser:
if m:
return cls.get_literal_string(data, m.end())
# return None, offset # fallback (only for debugging)
raise PdfFormatError("unrecognized object: " + repr(data[offset : offset + 32]))
msg = "unrecognized object: " + repr(data[offset : offset + 32])
raise PdfFormatError(msg)
re_lit_str_token = re.compile(
rb"(\\[nrtbf()\\])|(\\[0-9]{1,3})|(\\(\r\n|\r|\n))|(\r\n|\r|\n)|(\()|(\))"

View File

@ -491,7 +491,8 @@ def extract_dep(url, filename):
raise RuntimeError(msg)
tgz.extractall(sources_dir)
else:
raise RuntimeError("Unknown archive type: " + filename)
msg = "Unknown archive type: " + filename
raise RuntimeError(msg)
def write_script(name, lines):
@ -628,7 +629,8 @@ if __name__ == "__main__":
elif arg == "--srcdir":
sources_dir = os.path.sep + "src"
else:
raise ValueError("Unknown parameter: " + arg)
msg = "Unknown parameter: " + arg
raise ValueError(msg)
# dependency cache directory
os.makedirs(depends_dir, exist_ok=True)