errors.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import flask
  4. from werkzeug.exceptions import HTTPException
  5. from ._http import HTTPStatus
  6. __all__ = (
  7. "abort",
  8. "RestError",
  9. "ValidationError",
  10. "SpecsError",
  11. )
  12. def abort(code=HTTPStatus.INTERNAL_SERVER_ERROR, message=None, **kwargs):
  13. """
  14. Properly abort the current request.
  15. Raise a `HTTPException` for the given status `code`.
  16. Attach any keyword arguments to the exception for later processing.
  17. :param int code: The associated HTTP status code
  18. :param str message: An optional details message
  19. :param kwargs: Any additional data to pass to the error payload
  20. :raise HTTPException:
  21. """
  22. try:
  23. flask.abort(code)
  24. except HTTPException as e:
  25. if message:
  26. kwargs["message"] = str(message)
  27. if kwargs:
  28. e.data = kwargs
  29. raise
  30. class RestError(Exception):
  31. """Base class for all Flask-RESTX Errors"""
  32. def __init__(self, msg):
  33. self.msg = msg
  34. def __str__(self):
  35. return self.msg
  36. class ValidationError(RestError):
  37. """A helper class for validation errors."""
  38. pass
  39. class SpecsError(RestError):
  40. """A helper class for incoherent specifications."""
  41. pass