-
Notifications
You must be signed in to change notification settings - Fork 356
feat: add LangfuseError exception hierarchy #1908
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Yoel-qin
wants to merge
2
commits into
langfuse:main
Choose a base branch
from
Yoel-qin:feat/langfuse-error-hierarchy-906
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+147
−9
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| """Exception hierarchy for the Langfuse Python SDK. | ||
|
|
||
| All exceptions defined in hand-written SDK code derive from | ||
| :class:`LangfuseError`, so applications can catch every SDK-raised error with | ||
| a single ``except LangfuseError`` clause while fine-grained subclasses remain | ||
| available for callers that need to distinguish failure modes. Every class in | ||
| this hierarchy is also an ``Exception`` subclass, so existing | ||
| ``except Exception`` handlers keep working. | ||
|
|
||
| Errors raised by the generated API client (``langfuse.api``) are not part of | ||
| this hierarchy; they derive from the generated ``langfuse.api.core.ApiError`` | ||
| base instead. | ||
| """ | ||
|
|
||
| __all__ = ["AuthError", "LangfuseError"] | ||
|
|
||
|
|
||
| class LangfuseError(Exception): | ||
| """Base class for all exceptions raised by the Langfuse SDK.""" | ||
|
|
||
|
|
||
| class AuthError(LangfuseError): | ||
| """Raised when authentication with the Langfuse API fails. | ||
|
|
||
| Example: ``Langfuse.auth_check()`` raises this when the configured | ||
| credentials are accepted but resolve to no project. | ||
| """ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| """Tests for the Langfuse SDK exception hierarchy.""" | ||
|
|
||
| from types import SimpleNamespace | ||
| from unittest.mock import patch | ||
|
|
||
| import pytest | ||
|
|
||
| from langfuse import ( | ||
| APIError, | ||
| APIErrors, | ||
| AuthError, | ||
| Langfuse, | ||
| LangfuseError, | ||
| RegressionError, | ||
| ) | ||
|
|
||
|
|
||
| class TestExceptionHierarchy: | ||
| def test_all_sdk_errors_derive_from_langfuse_error(self): | ||
| for error_cls in (AuthError, APIError, APIErrors, RegressionError): | ||
| assert issubclass(error_cls, LangfuseError) | ||
| assert issubclass(error_cls, Exception) | ||
|
|
||
| def test_api_error_str_is_unchanged(self): | ||
| error = APIError(401, "Unauthorized", {"code": "invalid_api_key"}) | ||
|
|
||
| assert str(error) == "Unauthorized (401): {'code': 'invalid_api_key'}" | ||
|
|
||
| def test_api_errors_str_is_unchanged(self): | ||
| error = APIErrors([APIError(400, "Bad request"), APIError(429, "Rate limited")]) | ||
|
|
||
| assert ( | ||
| str(error) == "[Langfuse] Bad request (400): None, Rate limited (429): None" | ||
| ) | ||
|
|
||
|
|
||
| class TestAuthCheck: | ||
| def test_auth_check_raises_auth_error_when_no_projects(self): | ||
| client = Langfuse(public_key="test_pk", secret_key="test_sk") | ||
|
|
||
| with ( | ||
| patch.object( | ||
| client.api.projects, | ||
| "get", | ||
| return_value=SimpleNamespace(data=[]), | ||
| ), | ||
| pytest.raises(AuthError, match="no project found"), | ||
| ): | ||
| client.auth_check() | ||
|
|
||
| def test_auth_check_error_is_catchable_as_langfuse_error(self): | ||
| client = Langfuse(public_key="test_pk", secret_key="test_sk") | ||
|
|
||
| with ( | ||
| patch.object( | ||
| client.api.projects, | ||
| "get", | ||
| return_value=SimpleNamespace(data=[]), | ||
| ), | ||
| pytest.raises(LangfuseError), | ||
| ): | ||
| client.auth_check() | ||
|
|
||
| def test_auth_check_returns_true_when_projects_exist(self): | ||
| client = Langfuse(public_key="test_pk", secret_key="test_sk") | ||
|
|
||
| with patch.object( | ||
| client.api.projects, | ||
| "get", | ||
| return_value=SimpleNamespace(data=[SimpleNamespace(id="p1")]), | ||
| ): | ||
| assert client.auth_check() is True | ||
|
|
||
| def test_auth_check_maps_fern_unauthorized_error_to_auth_error(self): | ||
| from langfuse.api import UnauthorizedError | ||
|
|
||
| client = Langfuse(public_key="test_pk", secret_key="test_sk") | ||
| fern_error = UnauthorizedError(body={"error": "Unauthorized"}) | ||
|
|
||
| with ( | ||
| patch.object(client.api.projects, "get", side_effect=fern_error), | ||
| pytest.raises(AuthError, match="invalid credentials") as excinfo, | ||
| ): | ||
| client.auth_check() | ||
|
|
||
| assert isinstance(excinfo.value.__cause__, UnauthorizedError) | ||
|
|
||
| def test_auth_check_propagates_non_auth_fern_errors_unchanged(self): | ||
| from langfuse.api import NotFoundError | ||
|
|
||
| client = Langfuse(public_key="test_pk", secret_key="test_sk") | ||
| fern_error = NotFoundError(body={"error": "Not found"}) | ||
|
|
||
| with ( | ||
| patch.object(client.api.projects, "get", side_effect=fern_error), | ||
| pytest.raises(NotFoundError), | ||
| ): | ||
| client.auth_check() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
projects.get()raises the generatedUnauthorizedErrorbefore this newAuthErrorbranch runs.UnauthorizedErroris not aLangfuseError, and the existing handler catches a different generated error class. Callers using the new hierarchy therefore cannot catch this authentication failure. Handle the 401 response asAuthErrorat this boundary.Knowledge Base Used: API client and service surface
Prompt To Fix With AI
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch — fixed in a57ebff, and it was subtler than the diff suggested: the generated
Errorclass the handler caught is itself just the generic 400 subclass of the fernApiErrorbase, soUnauthorizedError(a sibling subclass) escaped the handler entirely and reached callers raw, skipping even thehandle_fern_exceptionlogging.auth_check()now catchesApiErrorinstead, raises a chainedAuthErrorforUnauthorizedError, and re-raises everything else unchanged (so non-auth fern errors keep their exact types). Added tests for the 401 →AuthErrormapping and for aNotFoundErrorpropagating unchanged.Note: the same
except Errorpattern exists at a few other call sites inclient.py(score/trace-tag helpers). I left those untouched to keep this PR scoped to the auth boundary — happy to do a separate pass converting them if that's wanted.