@@ -47,6 +47,13 @@ impl AiService {
4747 let response_text = response. text ( ) . await ?;
4848
4949 if !status. is_success ( ) {
50+ // Try to parse error response as JSON first
51+ if let Ok ( ai_response) = serde_json:: from_str :: < AiResponse > ( & response_text) {
52+ if let Some ( error) = ai_response. error {
53+ anyhow:: bail!( "AI API returned error: {}" , error) ;
54+ }
55+ }
56+ // If JSON parsing fails, return the generic error
5057 anyhow:: bail!(
5158 "AI API request failed with status: {} - Response: {}" ,
5259 status,
@@ -171,4 +178,67 @@ mod tests {
171178
172179 mock. assert_async ( ) . await ;
173180 }
181+
182+ #[ tokio:: test]
183+ async fn test_ai_service_request_format ( ) {
184+ let mut server = Server :: new_async ( ) . await ;
185+
186+ // Mock the API to capture what we're sending
187+ let mock = server
188+ . mock ( "POST" , "/api/getAnswer" )
189+ . match_header ( "content-type" , "application/json" )
190+ . match_body ( r#"{"question":"test question"}"# )
191+ . with_status ( 200 )
192+ . with_header ( "content-type" , "application/json" )
193+ . with_body (
194+ json ! ( {
195+ "answer" : "Test response"
196+ } )
197+ . to_string ( ) ,
198+ )
199+ . create_async ( )
200+ . await ;
201+
202+ let mut ai_service = AiService :: new ( ) ;
203+ ai_service. api_url = server. url ( ) + "/api/getAnswer" ;
204+
205+ let result = ai_service. query ( "test question" ) . await ;
206+
207+ assert ! ( result. is_ok( ) ) ;
208+ assert_eq ! ( result. unwrap( ) , "Test response" ) ;
209+
210+ mock. assert_async ( ) . await ;
211+ }
212+
213+ #[ tokio:: test]
214+ async fn test_ai_service_error_with_json_response ( ) {
215+ let mut server = Server :: new_async ( ) . await ;
216+
217+ // Mock error response with 500 status and JSON error
218+ let mock = server
219+ . mock ( "POST" , "/api/getAnswer" )
220+ . with_status ( 500 )
221+ . with_header ( "content-type" , "application/json" )
222+ . with_body (
223+ json ! ( {
224+ "error" : "Failed to process query"
225+ } )
226+ . to_string ( ) ,
227+ )
228+ . create_async ( )
229+ . await ;
230+
231+ let mut ai_service = AiService :: new ( ) ;
232+ ai_service. api_url = server. url ( ) + "/api/getAnswer" ;
233+
234+ let result = ai_service. query ( "invalid question" ) . await ;
235+
236+ assert ! ( result. is_err( ) ) ;
237+ assert ! ( result
238+ . unwrap_err( )
239+ . to_string( )
240+ . contains( "AI API returned error: Failed to process query" ) ) ;
241+
242+ mock. assert_async ( ) . await ;
243+ }
174244}
0 commit comments