{"record":{"id":"a05931dc9175f7bb","repo":"mastra-ai/mastra","slug":"error-message-mastraerror-rethrown-with-mapped-st-a05931","errorCode":null,"errorMessage":"error.message (MastraError rethrown with mapped status in AI generation route)","messagePattern":"error\\.message \\(MastraError rethrown with mapped status in AI generation route\\)","errorType":"http","errorClass":"HTTPException","httpStatus":null,"severity":"error","filePath":"packages/server/src/server/handlers/datasets.ts","lineNumber":1389,"sourceCode":"          input = JSON.parse(item.input);\n        } catch {\n          // Keep as string if not valid JSON\n        }\n        let groundTruth: unknown = item.groundTruth;\n        if (item.groundTruth) {\n          try {\n            groundTruth = JSON.parse(item.groundTruth);\n          } catch {\n            // Keep as string if not valid JSON\n          }\n        }\n        return { input, groundTruth };\n      });\n\n      return { items };\n    } catch (error) {\n      if (error instanceof MastraError) {\n        throw new HTTPException(getHttpStatusForMastraError(error.id) as StatusCode, { message: error.message });\n      }\n      return handleError(error, 'Error generating dataset items');\n    }\n  },\n});\n\n// ============================================================================\n// Failure Clustering\n// ============================================================================\n\nconst CLUSTER_FAILURES_SYSTEM_PROMPT = `You are an AI evaluation expert specializing in failure analysis. Given a set of failure items from an AI agent experiment, identify common failure patterns and assign descriptive tags to each item.\n\nFor each cluster you identify, provide:\n- A short, descriptive tag label (2-5 words, lowercase, hyphenated, e.g., \"no-tool-usage\", \"hallucination\")\n- A description explaining the common failure pattern\n- The IDs of items that belong to this cluster\n\nAlso return a \"proposedTags\" array mapping each item ID to the tags you recommend, along with a brief \"reason\" explaining WHY those tags apply to that specific item. The reason should reference concrete evidence from the item's input/output/error.","sourceCodeStart":1371,"sourceCodeEnd":1407,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/server/src/server/handlers/datasets.ts#L1371-L1407","documentation":"When AI dataset item generation fails, the route inspects the thrown error. If it is a MastraError (the library's structured error type carrying a domain/id), the handler rethrows it as an HTTPException whose status code is derived from the error id via getHttpStatusForMastraError, preserving error.message as the response body message. Any non-MastraError is routed to the generic handleError fallback. Developers see the original Mastra error text surfaced verbatim in the HTTP response.","triggerScenarios":"POSTing to the AI generate-dataset-items route when the underlying generation workflow/agent throws a MastraError — e.g. model provider failure, invalid prompt/schema configuration, or internal workflow domain error whose id maps to a status like 400/429/500.","commonSituations":"Misconfigured model credentials or missing model in the generation agent, malformed request payload rejected by a schema-validated step, or a storage/agent domain raising MastraError mid-run; the client receives a non-JSON or JSON HTTPException body with the raw Mastra message.","solutions":["Read error.message in the response and the mapped status code to identify the originating MastraError domain id","Fix the underlying cause (model config, credentials, request payload) that made the generation step throw","If the message is opaque, enable server-side logging on the generation route to capture the full MastraError stack","Ensure the client handles the mapped HTTP status rather than assuming 400/500"],"exampleFix":"// client sees opaque error\nconst res = await fetch('/api/datasets/generate', { method: 'POST', body });\nif (!res.ok) console.error(await res.text());\n// after — surface status + message deliberately\nif (!res.ok) {\n  const { message } = await res.json();\n  throw new Error(`generate failed (${res.status}): ${message}`);\n}","handlingStrategy":"try-catch","validationCode":"// validate payload before calling\nconst body = { agentId, count };\nif (!agentId || !Number.isInteger(count) || count <= 0) throw new Error('invalid generate request');","typeGuard":"function isMastraErrorBody(b: unknown): b is { message: string } {\n  return typeof b === 'object' && b !== null && 'message' in b && typeof (b as any).message === 'string';\n}","tryCatchPattern":"try {\n  const res = await fetch('/api/datasets/generate', { method: 'POST', body: JSON.stringify(payload) });\n  if (!res.ok) {\n    const body = await res.json().catch(() => null);\n    throw new Error(`generate failed (${res.status}): ${isMastraErrorBody(body) ? body.message : res.statusText}`);\n  }\n} catch (err) {\n  logger.error({ err }, 'dataset generation failed');\n}","preventionTips":["Validate agent/model configuration before invoking generation","Handle 429/503 mapped statuses with retry + backoff","Log the full response body server- and client-side for diagnosis"],"tags":["server","http","error-mapping","datasets"],"backgroundTag":"mastra-error-rethrow","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}