Skip to content

feat: generate Exception subclass per API error type#737

Draft
vdusek wants to merge 2 commits intomasterfrom
feat/api-error-subclasses
Draft

feat: generate Exception subclass per API error type#737
vdusek wants to merge 2 commits intomasterfrom
feat/api-error-subclasses

Conversation

@vdusek
Copy link
Copy Markdown
Contributor

@vdusek vdusek commented Apr 17, 2026

Summary

Addresses #423. Each ErrorType enum member from the OpenAPI spec now has a matching ApifyApiError subclass (e.g. RecordNotFoundError, ActorNotFoundError, InsufficientPermissionsError, ...) auto-generated into src/apify_client/_generated_errors.py by the existing model-postprocess step.

ApifyApiError.__new__ dispatches to the right subclass based on the response's error.type. Unknown types and unparsable bodies fall through to the base ApifyApiError. Direct subclass instantiation bypasses dispatch. except ApifyApiError handlers keep working because every generated class inherits from ApifyApiError.

Naming

  • RECORD_NOT_FOUNDRecordNotFoundError
  • BILLING_SYSTEM_ERRORBillingSystemError (trailing _ERROR stripped)
  • FIELD_3D_SECURE_AUTH_FAILEDField3DSecureAuthFailedError (digit parts preserved)
  • NOT_IMPLEMENTEDApiNotImplementedError (Api prefix to avoid shadowing the builtin)
  • SCHEMA_VALIDATION / SCHEMA_VALIDATION_ERRORSchemaValidationError / SchemaValidationErrorError (collision fallback)

Usage

from apify_client.errors import ApifyApiError, RecordNotFoundError

try:
    client.dataset(id).get()
except RecordNotFoundError:
    ...
except ApifyApiError:  # still matches everything else
    ...

Migration note

Minor behavior change for 3.0 scope: constructing ApifyApiError(response, ...) directly now returns an instance of the matching subclass rather than always ApifyApiError itself. except ApifyApiError is unaffected; tests constructing the base class and asserting type(exc) is ApifyApiError would need updates.

Addresses #423. Each `ErrorType` enum member from the OpenAPI spec now has a
matching `ApifyApiError` subclass (e.g. `RecordNotFoundError`) generated into
`_generated_errors.py`. `ApifyApiError.__new__` dispatches to the right
subclass based on the response's `error.type`, so `except ApifyApiError` keeps
working while `except RecordNotFoundError` becomes possible.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@vdusek vdusek added adhoc Ad-hoc unplanned task added during the sprint. t-tooling Issues with this label are in the ownership of the tooling team. labels Apr 17, 2026
@vdusek vdusek self-assigned this Apr 17, 2026
@github-actions github-actions bot added this to the 138th sprint - Tooling team milestone Apr 17, 2026
@github-actions github-actions bot added the tested Temporary label used only programatically for some analytics. label Apr 17, 2026
@codecov
Copy link
Copy Markdown

codecov bot commented Apr 17, 2026

Codecov Report

❌ Patch coverage is 99.75460% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.91%. Comparing base (3d4ce3f) to head (189e0aa).

Files with missing lines Patch % Lines
src/apify_client/errors.py 93.75% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #737      +/-   ##
==========================================
+ Coverage   95.26%   95.91%   +0.64%     
==========================================
  Files          45       46       +1     
  Lines        5115     5918     +803     
==========================================
+ Hits         4873     5676     +803     
  Misses        242      242              
Flag Coverage Δ
integration 95.91% <99.75%> (+0.64%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…d __init__

`__new__` used to parse `response.json()` for dispatch and `__init__` parsed
it again for attribute assignment. Now `__new__` stashes the parsed `error`
dict on the instance and `__init__` reads it, so each raised error parses
the body once. Also trims the stale star-import comment.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@vdusek vdusek requested review from Pijukatel and janbuchar April 17, 2026 11:16
@vdusek
Copy link
Copy Markdown
Contributor Author

vdusek commented Apr 17, 2026

Let me guys know whether you think this is worth it. Currently, I'm slightly more inclined not to do it and keep the status quo. Since the API type errors are just general strings, they can often change.

@janbuchar
Copy link
Copy Markdown
Contributor

Arguments in favor

  1. Better DX - easier to catch individual types of exception, while you can still just catch ApifyApiError if you don't care much
  2. Better DX - the exception name has a non-generic name, and that's the first thing you look at when you see an exception traceback in logs

Arguments against

  1. It' a lot of generated code
  2. We need to maintain the generator
  3. If an error type disappears from a response object, it might get deleted from the code base, which is a breaking change (but it's also a breaking change in the API, so I'm not sure about the validity of this concern)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

adhoc Ad-hoc unplanned task added during the sprint. t-tooling Issues with this label are in the ownership of the tooling team. tested Temporary label used only programatically for some analytics.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants