Browse Source

Improve error handling and validation in Depends

pull/14281/head
Adeniran John 9 months ago
parent
commit
35fccdb7ac
  1. 11
      fastapi/params.py

11
fastapi/params.py

@ -780,20 +780,21 @@ class Depends:
# Check if dependency is callable # Check if dependency is callable
if not callable(dependency): if not callable(dependency):
# Provide helpful error based on the type
dep_type = type(dependency).__name__ dep_type = type(dependency).__name__
error_msg = f"Depends() expects a callable (function or class), but received {dep_type}. " error_msg = f"Depends() expects a callable (function or class), but received {dep_type}. "
# Add specific hints for common mistakes
if isinstance(dependency, (dict, list, str, int, float, bool)): if isinstance(dependency, (dict, list, str, int, float, bool)):
error_msg += ( error_msg += (
"\n\nIt looks like you may have called the dependency function instead of passing it. " "\n\nIt looks like you may have called the dependency function instead of passing it. "
"\n✓ Correct: Depends(my_function)" "\n✓ Correct: Depends(my_function)"
"\n✗ Wrong: Depends(my_function())" "\n✗ Wrong: Depends(my_function())"
) )
elif callable(dependency): else:
# Might be an instance of a callable class # Might be a user-defined object or instance of a callable class
error_msg += "\n\nIf you're using a callable class, make sure to pass the class itself or a callable instance." error_msg += (
"\n\nIf you're using a callable class, make sure to pass the class itself or "
"a callable instance (i.e., define __call__)."
)
raise TypeError(error_msg) raise TypeError(error_msg)

Loading…
Cancel
Save