Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import re
  2. import sys
  3. from collections.abc import Mapping
  4. from typing import Any
  5. from flask import Blueprint, Flask, current_app, got_request_exception
  6. from flask_restx import Api
  7. from werkzeug.exceptions import HTTPException
  8. from werkzeug.http import HTTP_STATUS_CODES
  9. from configs import dify_config
  10. from core.errors.error import AppInvokeQuotaExceededError
  11. def http_status_message(code):
  12. return HTTP_STATUS_CODES.get(code, "")
  13. def register_external_error_handlers(api: Api) -> None:
  14. @api.errorhandler(HTTPException)
  15. def handle_http_exception(e: HTTPException):
  16. got_request_exception.send(current_app, exception=e)
  17. # If Werkzeug already prepared a Response, just use it.
  18. if getattr(e, "response", None) is not None:
  19. return e.response
  20. status_code = getattr(e, "code", 500) or 500
  21. # Build a safe, dict-like payload
  22. default_data = {
  23. "code": re.sub(r"(?<!^)(?=[A-Z])", "_", type(e).__name__).lower(),
  24. "message": getattr(e, "description", http_status_message(status_code)),
  25. "status": status_code,
  26. }
  27. if default_data["message"] == "Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)":
  28. default_data["message"] = "Invalid JSON payload received or JSON payload is empty."
  29. # Use headers on the exception if present; otherwise none.
  30. headers = {}
  31. exc_headers = getattr(e, "headers", None)
  32. if exc_headers:
  33. headers.update(exc_headers)
  34. # Payload per status
  35. if status_code == 406 and api.default_mediatype is None:
  36. data = {"code": "not_acceptable", "message": default_data["message"], "status": status_code}
  37. return data, status_code, headers
  38. elif status_code == 400:
  39. msg = default_data["message"]
  40. if isinstance(msg, Mapping) and msg:
  41. # Convert param errors like {"field": "reason"} into a friendly shape
  42. param_key, param_value = next(iter(msg.items()))
  43. data = {
  44. "code": "invalid_param",
  45. "message": str(param_value),
  46. "params": param_key,
  47. "status": status_code,
  48. }
  49. else:
  50. data = {**default_data}
  51. data.setdefault("code", "unknown")
  52. return data, status_code, headers
  53. else:
  54. data = {**default_data}
  55. data.setdefault("code", "unknown")
  56. # If you need WWW-Authenticate for 401, add it to headers
  57. if status_code == 401:
  58. headers["WWW-Authenticate"] = 'Bearer realm="api"'
  59. return data, status_code, headers
  60. @api.errorhandler(ValueError)
  61. def handle_value_error(e: ValueError):
  62. got_request_exception.send(current_app, exception=e)
  63. status_code = 400
  64. data = {"code": "invalid_param", "message": str(e), "status": status_code}
  65. return data, status_code
  66. @api.errorhandler(AppInvokeQuotaExceededError)
  67. def handle_quota_exceeded(e: AppInvokeQuotaExceededError):
  68. got_request_exception.send(current_app, exception=e)
  69. status_code = 429
  70. data = {"code": "too_many_requests", "message": str(e), "status": status_code}
  71. return data, status_code
  72. @api.errorhandler(Exception)
  73. def handle_general_exception(e: Exception):
  74. got_request_exception.send(current_app, exception=e)
  75. status_code = 500
  76. data: dict[str, Any] = getattr(e, "data", {"message": http_status_message(status_code)})
  77. # 🔒 Normalize non-mapping data (e.g., if someone set e.data = Response)
  78. if not isinstance(data, Mapping):
  79. data = {"message": str(e)}
  80. data.setdefault("code", "unknown")
  81. data.setdefault("status", status_code)
  82. # Log stack
  83. exc_info: Any = sys.exc_info()
  84. if exc_info[1] is None:
  85. exc_info = None
  86. current_app.log_exception(exc_info) # ty: ignore [invalid-argument-type]
  87. return data, status_code
  88. class ExternalApi(Api):
  89. _authorizations = {
  90. "Bearer": {
  91. "type": "apiKey",
  92. "in": "header",
  93. "name": "Authorization",
  94. "description": "Type: Bearer {your-api-key}",
  95. }
  96. }
  97. def __init__(self, app: Blueprint | Flask, *args, **kwargs):
  98. kwargs.setdefault("authorizations", self._authorizations)
  99. kwargs.setdefault("security", "Bearer")
  100. kwargs["add_specs"] = dify_config.SWAGGER_UI_ENABLED
  101. kwargs["doc"] = dify_config.SWAGGER_UI_PATH if dify_config.SWAGGER_UI_ENABLED else False
  102. # manual separate call on construction and init_app to ensure configs in kwargs effective
  103. super().__init__(app=None, *args, **kwargs) # type: ignore
  104. self.init_app(app, **kwargs)
  105. register_external_error_handlers(self)