@@ -259,6 +259,32 @@ public function test_exception_in_terminating_method_caught_and_returned(): void
259259 $ this ->assertNotEmpty ( $ error_data ['exception_class ' ] );
260260 }
261261
262+ /**
263+ * Test that exception in chained method is caught and returned by the terminating method as WP_Error.
264+ */
265+ public function test_exception_in_chained_method_caught_and_returned_by_terminating_method (): void {
266+ $ registry = AiClient::defaultRegistry ();
267+ $ prompt_builder = new Prompt_Builder_With_WP_Error ( $ registry );
268+
269+ $ result = $ prompt_builder
270+ ->with_text ( 'Start of prompt ' )
271+ ->with_file ( 'https://example.com/img.jpg ' , 'image/jpeg ' )
272+ // The line below is incorrect: Only provider and model ID must be given.
273+ ->using_model_preference ( array ( 'test-provider ' , 'test-model ' , 'test-version ' ) )
274+ ->using_system_instruction ( 'Be helpful ' )
275+ ->generate_text ();
276+
277+ $ this ->assertInstanceOf ( WP_Error::class, $ result , 'generate_text should return WP_Error when exception occurs ' );
278+ $ this ->assertSame ( 'prompt_builder_error ' , $ result ->get_error_code () );
279+ $ this ->assertSame ( 'Model preference tuple must contain model identifier and provider ID. ' , $ result ->get_error_message () );
280+
281+ // Check that error data contains exception class.
282+ $ error_data = $ result ->get_error_data ();
283+ $ this ->assertIsArray ( $ error_data );
284+ $ this ->assertArrayHasKey ( 'exception_class ' , $ error_data );
285+ $ this ->assertNotEmpty ( $ error_data ['exception_class ' ] );
286+ }
287+
262288 /**
263289 * Test that the wrapped builder is properly configured with the registry.
264290 */
0 commit comments