errors.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """Error classes used by simplejson
  2. """
  3. __all__ = ['JSONDecodeError']
  4. def linecol(doc, pos):
  5. lineno = doc.count('\n', 0, pos) + 1
  6. if lineno == 1:
  7. colno = pos + 1
  8. else:
  9. colno = pos - doc.rindex('\n', 0, pos)
  10. return lineno, colno
  11. def errmsg(msg, doc, pos, end=None):
  12. lineno, colno = linecol(doc, pos)
  13. msg = msg.replace('%r', repr(doc[pos:pos + 1]))
  14. if end is None:
  15. fmt = '%s: line %d column %d (char %d)'
  16. return fmt % (msg, lineno, colno, pos)
  17. endlineno, endcolno = linecol(doc, end)
  18. fmt = '%s: line %d column %d - line %d column %d (char %d - %d)'
  19. return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end)
  20. class JSONDecodeError(ValueError):
  21. """Subclass of ValueError with the following additional properties:
  22. msg: The unformatted error message
  23. doc: The JSON document being parsed
  24. pos: The start index of doc where parsing failed
  25. end: The end index of doc where parsing failed (may be None)
  26. lineno: The line corresponding to pos
  27. colno: The column corresponding to pos
  28. endlineno: The line corresponding to end (may be None)
  29. endcolno: The column corresponding to end (may be None)
  30. """
  31. # Note that this exception is used from _speedups
  32. def __init__(self, msg, doc, pos, end=None):
  33. ValueError.__init__(self, errmsg(msg, doc, pos, end=end))
  34. self.msg = msg
  35. self.doc = doc
  36. self.pos = pos
  37. self.end = end
  38. self.lineno, self.colno = linecol(doc, pos)
  39. if end is not None:
  40. self.endlineno, self.endcolno = linecol(doc, end)
  41. else:
  42. self.endlineno, self.endcolno = None, None
  43. def __reduce__(self):
  44. return self.__class__, (self.msg, self.doc, self.pos, self.end)