Dispatch AiExceptionEvent when a provider throws an exception

Created on 21 August 2025, 7 days ago

Problem/Motivation

We're reaching a moment where projects are implementing the AI module and it's features (like XB AI) and third-parties want to customize the interaction. For example, I want to customize the response for exceeding budget/quota is exceeded. The XB AI can catch the exception ( 🐛 Uncaught exceptions when determining solvability of AI request Active ) but would need its own API for customizing.

Steps to reproduce (required for bugs, but not feature requests)

Use OpenAI module and burn through quota, see direct error message from provider.

Proposed resolution

- Create AiExceptionEvent (see below
- Dispatch in wrapperCall where there is the large try/catch block and throw the exception after dispatch
- Move the logging for each exception type into an event subscriber


final class AiExceptionEvent extends \Symfony\Contracts\EventDispatcher\Event {
  
  private string $message;

  public function __construct(
    public readonly \Exception $exception,
  ) {
    $this->message = $exception->getMessage();
  }

  /**
   * @param string $message
   */
  public function setMessage(string $message): void {
    $this->message = $message;
  }

  /**
   * @return \Exception
   */
  public function getException(): Exception {
    return new \Drupal\ai\Exception\AiResponseErrorException(
      $this->message,
      $this->exception->getCode(),
      $this->exception
    );
  }

}

I guess the problem is that the thrown exception is then always AiResponseErrorException and if callers want the specific exception they always have to call getPrevious. Maybe that's OK?

Remaining tasks

Optional: Other details as applicable (e.g., User interface changes, API changes, Data model changes)

Feature request
Status

Active

Version

2.0

Component

...to be triaged

Created by

🇺🇸United States mglaman WI, USA

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024