trytond.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import sentry_sdk
  2. from sentry_sdk.integrations import Integration
  3. from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware
  4. from sentry_sdk.utils import ensure_integration_enabled, event_from_exception
  5. from sentry_sdk.integrations import DidNotEnable
  6. try:
  7. from trytond.exceptions import TrytonException # type: ignore
  8. from trytond.wsgi import app # type: ignore
  9. except ImportError:
  10. raise DidNotEnable("Trytond is not installed.")
  11. # TODO: trytond-worker, trytond-cron and trytond-admin intergations
  12. class TrytondWSGIIntegration(Integration):
  13. identifier = "trytond_wsgi"
  14. origin = f"auto.http.{identifier}"
  15. def __init__(self) -> None:
  16. pass
  17. @staticmethod
  18. def setup_once() -> None:
  19. app.wsgi_app = SentryWsgiMiddleware(
  20. app.wsgi_app,
  21. span_origin=TrytondWSGIIntegration.origin,
  22. )
  23. @ensure_integration_enabled(TrytondWSGIIntegration)
  24. def error_handler(e: Exception) -> None:
  25. if isinstance(e, TrytonException):
  26. return
  27. else:
  28. client = sentry_sdk.get_client()
  29. event, hint = event_from_exception(
  30. e,
  31. client_options=client.options,
  32. mechanism={"type": "trytond", "handled": False},
  33. )
  34. sentry_sdk.capture_event(event, hint=hint)
  35. # Expected error handlers signature was changed
  36. # when the error_handler decorator was introduced
  37. # in Tryton-5.4
  38. if hasattr(app, "error_handler"):
  39. @app.error_handler
  40. def _(app, request, e): # type: ignore
  41. error_handler(e)
  42. else:
  43. app.error_handlers.append(error_handler)