Skip to content

Conversation

Ref34t
Copy link
Contributor

@Ref34t Ref34t commented Sep 1, 2025

Summary
Implements exception hierarchy to improve error handling across the WordPress AI Client ecosystem, directly addressing feedback from PR 2 in https://github.com/WordPress/wp-ai-client

Changes

New Exception Classes

  • AiClientExceptionInterface - Base interface for catch-all exception handling
  • NetworkException - HTTP transport errors, connection failures, timeouts
  • RequestException - API authentication failures, rate limiting, malformed requests
  • InvalidArgumentException - Project-scoped extension of \InvalidArgumentException
  • RuntimeException - Project-scoped extension of \RuntimeException

Updated Code

  • Updated existing exception usage in AiClient.php, GenerativeAiResult.php, FunctionResponse.php
  • Modified ResponseException to extend RequestException for better categorization
  • Added comprehensive test coverage

Benefits

Unified Exception Handling:

try {
    $result = AiClient::prompt('Generate content')->generateText();
} catch (AiClientExceptionInterface $e) {
    // Catches ALL AI Client exceptions
}

Better Error Categorization:

  • Network issues → NetworkException
  • API/Auth issues → RequestException
  • Invalid arguments → InvalidArgumentException

Related

Addresses feedback from 2 review comments about improving exception handling for wp-ai-client integration. https://github.com/WordPress/wp-ai-client

@Ref34t
Copy link
Contributor Author

Ref34t commented Sep 1, 2025

@felixarntz This implements the exception hierarchy you suggested in PR 2 in the wp-ai-client review. Now developers can catch all AI Client exceptions with catch (AiClientExceptionInterface $e) for unified error handling, while still having specific exception types for different error categories (network, request, validation). The implementation is minimal and focused - exactly what was requested for better WP-ai-client integration.

@Ref34t Ref34t marked this pull request as ready for review September 1, 2025 13:28
@felixarntz felixarntz added the [Type] Enhancement A suggestion for improvement. label Sep 1, 2025
Copy link
Member

@felixarntz felixarntz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Ref34t Thank you for getting this started!

A few points of feedback below, and one higher-level point here: I think we should put the exceptions into specific directories. For example:

  • InvalidArgumentException and RuntimeException into src/Common/Exception
  • NetworkException and RequestException into src/Providers/Http/Exception (where we already have ResponseException)

@JasonTheAdams It would be great to get your review as well - including regarding my own feedback.

*
* @since 0.2.0
*/
class NetworkException extends RuntimeException implements AiClientExceptionInterface
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this exception class used for? We should only introduce exceptions that we have concrete usage for.

I can see how a NetworkException might be useful, but then we should also make sure it's used where applicable.

*
* @since 0.2.0
*/
class RequestException extends RuntimeException implements AiClientExceptionInterface
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What would this class be used for? I'm thinking that RequestException is most likely only relevant for bad request data (i.e. as an extension of InvalidArgumentException).

Similarly to my other comment, we need to actually use it if we add it here. There are at least several places in the provider implementation code or its abstract base classes where this could be used.

I think this would also be good to throw in scenarios when a Response comes back with a 400 Bad Request status code. In that case it means an invalid argument was set that our code didn't catch, but the API did.


/**
* Exception class for HTTP response errors.
*
* @since 0.1.0
*/
class ResponseException extends Exception
class ResponseException extends RequestException
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shouldn't extend RequestException - a ResponseException is definitely something different.

I think the main use-case for ResponseException is when the response data is unexpected - which should never happen, unless a provider changed in ways our code is not aware of. That's IMO the primary use-case for this.

@JasonTheAdams
Copy link
Member

I agree with @felixarntz! I like the direction, but we need to see these exceptions being used in a few places to indicate their concrete usage.

Copy link

github-actions bot commented Sep 2, 2025

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

Unlinked Accounts

The following contributors have not linked their GitHub and WordPress.org accounts: @[email protected].

Contributors, please read how to link your accounts to ensure your work is properly credited in WordPress releases.

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Unlinked contributors: [email protected].

Co-authored-by: felixarntz <[email protected]>
Co-authored-by: JasonTheAdams <[email protected]>
Co-authored-by: Ref34t <[email protected]>

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

@Ref34t
Copy link
Contributor Author

Ref34t commented Sep 2, 2025

@felixarntz @JasonTheAdams
I've spent some time refactoring and improving the enhancements, you can see below what I did:

Architectural Reorganization

Moved exceptions to proper directories:

  • InvalidArgumentException & RuntimeException → src/Common/Exception/
  • NetworkException & RequestException → src/Providers/Http/Exception/
  • Updated 50+ import statements across the entire codebase

Concrete Usage Examples

  • NetworkException: PSR-18 network error handling in HttpTransporter::send()
  • RequestException: 400 Bad Request response handling in HttpTransporter::send()
  • ResponseException: Missing API data handling in OpenAiModelMetadataDirectory
  • InvalidArgumentException: 50+ validation locations throughout codebase
  • RuntimeException: 40+ operational error locations throughout codebase

Proper Inheritance

Fixed inheritance relationships:

  • RequestException extends InvalidArgumentException (for bad request data validation)
  • ResponseException extends RuntimeException (for unexpected provider responses)
  • NetworkException extends RuntimeException (for network connectivity issues)

Enhanced Developer Experience (Static factory methods suggestion)

"Simply adding static from* methods to the various *Exception classes"

RequestException (3 methods):

RequestException::fromInvalidParam('OpenAI', 'temperature', 'Must be between 0 and 2');
RequestException::fromBadRequestResponse('OpenAI', $response);
RequestException::fromBadRequestToUri($uri, 'Invalid  JSON payload');

ResponseException (4 methods):

ResponseException::fromMissingData('OpenAI', 'data');
ResponseException::fromUnexpectedStructure('OpenAI', 'array', 'string');
ResponseException::fromMalformedResponse('OpenAI', 'Invalid JSON format');
ResponseException::fromParsingFailure('OpenAI', 'model list', $jsonException);

NetworkException (5 methods):

NetworkException::fromPsr18NetworkException($uri, $networkException);
NetworkException::fromConnectionFailure($uri, 'Connection refused');
NetworkException::fromTimeout($uri, 'request', 30);
NetworkException::fromDnsFailure('api.openai.com');
NetworkException::fromSslError($uri, 'Certificate  validation failed');

Kindly review and let me know if you have any concerned

Copy link
Member

@JasonTheAdams JasonTheAdams left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, @Ref34t! I'm not sure I see the point in creating our own InvalidArgumentException and RuntimeException classes. Do you, @felixarntz?

@felixarntz
Copy link
Member

@JasonTheAdams I do actually. It's simply about providing classes that can implement a common interface to identify "this is a specific exception from our PHP AI Client SDK".

Consuming code can then decide whether they want to catch e.g. RuntimeException and/or InvalidArgumentException or whether they want to do a single catch-all for "known" exceptions from our SDK only by catching AiClientExceptionInterface.

@JasonTheAdams
Copy link
Member

I like that, @felixarntz! Admittedly, I hadn't noticed the common Interface. I like that idea of being able to catch exceptions thrown by this package.

As a note, I think we should update the AGENTS.md to include a note that all exceptions should use our own, including primitives, and if a primitive doesn't exist it should be created. Not sure if we should add this elsewhere, too. If we're going down this road it's important that we're consistent.

@JasonTheAdams JasonTheAdams mentioned this pull request Sep 3, 2025
20 tasks
Copy link
Member

@JasonTheAdams JasonTheAdams left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm tracking now, @Ref34t! Good work!

I don't think we need all these static methods. As far as I can tell, there all used only one time. If that's the case, the abstraction isn't necessary and we can just let the implementing code determine the code, message, and such.

* This extends PHP's built-in InvalidArgumentException while implementing
* the AI Client exception interface for consistent catch handling.
*
* @since 0.2.0
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here and throughout, always use n.e.x.t because we don't want to assume we know the version something will be released in.

Suggested change
* @since 0.2.0
* @since n.e.x.t

Copy link
Member

@felixarntz felixarntz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Ref34t @JasonTheAdams I do think some of the static methods are useful - just not all of them.

Per my previous feedback, @Ref34t it would be great if you could review the codebase for where exceptions are thrown and update these exceptions to use the new exception classes and new static methods if applicable.

We should not introduce any exception classes or any static methods that aren't used anywhere - I think that's a good guiding principle. Therefore it's important that we update any existing exceptions to use the new approach, and if there are none for a specific exception or static method, we know it's not useful, at least not at this point.

@Ref34t
Copy link
Contributor Author

Ref34t commented Sep 4, 2025

very interesting Convo Champs @felixarntz @JasonTheAdams 🥇
I'll work it this today and bring the best from it based on my idea and your thoughts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
[Type] Enhancement A suggestion for improvement.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants