Skip to content

Commit

Permalink
STY: Add error module (#768)
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinThoma authored Apr 16, 2022
1 parent 31fc4ce commit 1f0fbf3
Show file tree
Hide file tree
Showing 15 changed files with 137 additions and 88 deletions.
6 changes: 6 additions & 0 deletions .isort.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[settings]
line_length=79
indent=' '
multi_line_output=3
length_sort=0
include_trailing_comma=True
25 changes: 25 additions & 0 deletions PyPDF2/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class PyPdfError(Exception):
pass


class PdfReadError(PyPdfError):
pass


class PageSizeNotDefinedError(PyPdfError):
pass


class PdfReadWarning(UserWarning):
pass


class PdfStreamError(PdfReadError):
pass


class ParseError(Exception):
pass


STREAM_TRUNCATED_PREMATURELY = "Stream has ended unexpectedly"
4 changes: 2 additions & 2 deletions PyPDF2/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@
from PyPDF2.constants import ImageAttributes as IA
from PyPDF2.constants import LzwFilterParameters as LZW
from PyPDF2.constants import StreamAttributes as SA

from .utils import PdfReadError, ord_, paethPredictor
from PyPDF2.errors import PdfReadError
from PyPDF2.utils import ord_, paethPredictor

if version_info < ( 3, 0 ):
from cStringIO import StringIO
Expand Down
51 changes: 31 additions & 20 deletions PyPDF2/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,22 @@

from PyPDF2.constants import FilterTypes as FT
from PyPDF2.constants import StreamAttributes as SA
from PyPDF2.utils import ERR_STREAM_TRUNCATED_PREMATURELY
from PyPDF2.errors import (
STREAM_TRUNCATED_PREMATURELY,
PdfReadError,
PdfStreamError,
)

from . import filters, utils
from .utils import (PdfStreamError, RC4_encrypt, b_, chr_, ord_,
readNonWhitespace, skipOverComment, u_)
from .utils import (
RC4_encrypt,
b_,
chr_,
ord_,
readNonWhitespace,
skipOverComment,
u_,
)

ObjectPrefix = b_('/<[tf(n%')
NumberSigns = b_('+-')
Expand Down Expand Up @@ -111,7 +122,7 @@ def writeToStream(self, stream, encryption_key):
def readFromStream(stream):
nulltxt = stream.read(4)
if nulltxt != b_("null"):
raise utils.PdfReadError("Could not read Null object")
raise PdfReadError("Could not read Null object")
return NullObject()
readFromStream = staticmethod(readFromStream) # type: ignore

Expand All @@ -134,7 +145,7 @@ def readFromStream(stream):
stream.read(1)
return BooleanObject(False)
else:
raise utils.PdfReadError('Could not read Boolean object')
raise PdfReadError('Could not read Boolean object')
readFromStream = staticmethod(readFromStream) # type: ignore


Expand All @@ -150,7 +161,7 @@ def readFromStream(stream, pdf):
arr = ArrayObject()
tmp = stream.read(1)
if tmp != b_("["):
raise utils.PdfReadError("Could not read array")
raise PdfReadError("Could not read array")
while True:
# skip leading whitespace
tok = stream.read(1)
Expand Down Expand Up @@ -200,23 +211,23 @@ def readFromStream(stream, pdf):
while True:
tok = stream.read(1)
if not tok:
raise PdfStreamError(ERR_STREAM_TRUNCATED_PREMATURELY)
raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
if tok.isspace():
break
idnum += tok
generation = b_("")
while True:
tok = stream.read(1)
if not tok:
raise PdfStreamError(ERR_STREAM_TRUNCATED_PREMATURELY)
raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
if tok.isspace():
if not generation:
continue
break
generation += tok
r = readNonWhitespace(stream)
if r != b_("R"):
raise utils.PdfReadError("Error reading indirect object reference at byte %s" % utils.hexStr(stream.tell()))
raise PdfReadError("Error reading indirect object reference at byte %s" % utils.hexStr(stream.tell()))
return IndirectObject(int(idnum), int(generation), pdf)
readFromStream = staticmethod(readFromStream) # type: ignore

Expand Down Expand Up @@ -306,7 +317,7 @@ def readHexStringFromStream(stream):
while True:
tok = readNonWhitespace(stream)
if not tok:
raise PdfStreamError(ERR_STREAM_TRUNCATED_PREMATURELY)
raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
if tok == b_(">"):
break
x += tok
Expand All @@ -327,7 +338,7 @@ def readStringFromStream(stream):
while True:
tok = stream.read(1)
if not tok:
raise PdfStreamError(ERR_STREAM_TRUNCATED_PREMATURELY)
raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
if tok == b_("("):
parens += 1
elif tok == b_(")"):
Expand Down Expand Up @@ -385,7 +396,7 @@ def readStringFromStream(stream):
# line break was escaped:
tok = b_('')
else:
raise utils.PdfReadError(r"Unexpected escaped string: %s" % tok)
raise PdfReadError(r"Unexpected escaped string: %s" % tok)
txt += tok
return createStringObject(txt)

Expand Down Expand Up @@ -477,7 +488,7 @@ def readFromStream(stream, pdf):
if debug: print((stream.tell()))
name = stream.read(1)
if name != NameObject.surfix:
raise utils.PdfReadError("name read error")
raise PdfReadError("name read error")
name += utils.readUntilRegex(stream, NameObject.delimiterPattern,
ignore_eof=True)
if debug: print(name)
Expand All @@ -494,7 +505,7 @@ def readFromStream(stream, pdf):
warnings.warn("Illegal character in Name Object", utils.PdfReadWarning)
return NameObject(name)
else:
raise utils.PdfReadError("Illegal character in Name Object")
raise PdfReadError("Illegal character in Name Object")

readFromStream = staticmethod(readFromStream) # type: ignore

Expand Down Expand Up @@ -559,7 +570,7 @@ def readFromStream(stream, pdf):
debug = False
tmp = stream.read(2)
if tmp != b_("<<"):
raise utils.PdfReadError("Dictionary read error at byte %s: stream must begin with '<<'" % utils.hexStr(stream.tell()))
raise PdfReadError("Dictionary read error at byte %s: stream must begin with '<<'" % utils.hexStr(stream.tell()))
data = {}
while True:
tok = readNonWhitespace(stream)
Expand All @@ -570,7 +581,7 @@ def readFromStream(stream, pdf):
skipOverComment(stream)
continue
if not tok:
raise PdfStreamError(ERR_STREAM_TRUNCATED_PREMATURELY)
raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)

if debug: print(("Tok:", tok))
if tok == b_(">"):
Expand All @@ -585,7 +596,7 @@ def readFromStream(stream, pdf):
data[key] = value
elif pdf.strict:
# multiple definitions of key not permitted
raise utils.PdfReadError("Multiple definitions in dictionary at byte %s for key %s" \
raise PdfReadError("Multiple definitions in dictionary at byte %s for key %s" \
% (utils.hexStr(stream.tell()), key))
else:
warnings.warn("Multiple definitions in dictionary at byte %s for key %s" \
Expand Down Expand Up @@ -632,7 +643,7 @@ def readFromStream(stream, pdf):
data["__streamdata__"] = data["__streamdata__"][:-1]
else:
stream.seek(pos, 0)
raise utils.PdfReadError("Unable to find 'endstream' marker after stream at byte %s." % utils.hexStr(stream.tell()))
raise PdfReadError("Unable to find 'endstream' marker after stream at byte %s." % utils.hexStr(stream.tell()))
else:
stream.seek(pos, 0)
if "__streamdata__" in data:
Expand Down Expand Up @@ -849,7 +860,7 @@ def getData(self):
return decoded._data

def setData(self, data):
raise utils.PdfReadError("Creating EncodedStreamObject is not currently supported")
raise PdfReadError("Creating EncodedStreamObject is not currently supported")


class RectangleObject(ArrayObject):
Expand Down Expand Up @@ -1079,7 +1090,7 @@ def __init__(self, title, page, typ, *args):
elif typ in [TF.FIT, TF.FIT_B]:
pass
else:
raise utils.PdfReadError("Unknown Destination Type: %r" % typ)
raise PdfReadError("Unknown Destination Type: %r" % typ)

def getDestArray(self):
return ArrayObject([self.raw_get('/Page'), self['/Type']] + [self[x] for x in ['/Left', '/Bottom', '/Right', '/Top', '/Zoom'] if x in self])
Expand Down
5 changes: 3 additions & 2 deletions PyPDF2/pagerange.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@

import re

from PyPDF2.errors import ParseError

from .utils import isString

_INT_RE = r"(0|-?[1-9]\d*)" # A decimal int, don't allow "-0".
PAGE_RANGE_RE = "^({int}|({int}?(:{int}?(:{int}?)?)))$".format(int=_INT_RE)
# groups: 12 34 5 6 7 8


class ParseError(Exception):
pass



PAGE_RANGE_HELP = """Remember, page indices start with zero.
Expand Down
Loading

0 comments on commit 1f0fbf3

Please sign in to comment.