exceptions.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # -*- coding: utf-8 -*-
  2. """
  3. flaskbb.core.exceptions
  4. ~~~~~~~~~~~~~~~~~~~~~~~
  5. Exceptions raised by flaskbb.core,
  6. forms the root of all exceptions in
  7. FlaskBB.
  8. :copyright: (c) 2014-2018 the FlaskBB Team
  9. :license: BSD, see LICENSE for more details
  10. """
  11. class BaseFlaskBBError(Exception):
  12. """
  13. Root exception for FlaskBB.
  14. """
  15. class ValidationError(BaseFlaskBBError):
  16. """
  17. Used to signal validation errors for things such as
  18. token verification, user registration, etc.
  19. :param str attribute: The attribute the validation error applies to,
  20. if the validation error applies to multiple attributes or to
  21. the entire object, this should be set to None
  22. :param str reason: Why the attribute, collection of attributes or object
  23. is invalid.
  24. """
  25. def __init__(self, attribute, reason):
  26. self.attribute = attribute
  27. self.reason = reason
  28. super(ValidationError, self).__init__((attribute, reason))
  29. class StopValidation(BaseFlaskBBError):
  30. """
  31. Raised from validation handlers to signal that
  32. validation should end immediately and no further
  33. processing should be done.
  34. Can also be used to communicate all errors
  35. raised during a validation run.
  36. :param reasons: A sequence of `(attribute, reason)` pairs explaining
  37. why the object is invalid.
  38. """
  39. def __init__(self, reasons):
  40. self.reasons = reasons
  41. super(StopValidation, self).__init__(reasons)
  42. class PersistenceError(BaseFlaskBBError):
  43. """
  44. Used to catch down errors when persisting models to the database instead
  45. of letting all issues percolate up, this should be raised from those
  46. exceptions without smashing their tracebacks. Example::
  47. try:
  48. db.session.add(new_user)
  49. db.session.commit()
  50. except Exception:
  51. raise PersistenceError("Couldn't save user account")
  52. """
  53. def accumulate_errors(caller, validators, throw=True):
  54. errors = []
  55. for validator in validators:
  56. try:
  57. caller(validator)
  58. except ValidationError as e:
  59. errors.append((e.attribute, e.reason))
  60. if len(errors) and throw:
  61. raise StopValidation(errors)
  62. return errors