mastra-ai/mastra · error · HTTPException

error.message (MastraError rethrown with mapped status in AI

Error message

error.message (MastraError rethrown with mapped status in AI generation route)

What it means

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.

Source

Thrown at packages/server/src/server/handlers/datasets.ts:1389

          input = JSON.parse(item.input);
        } catch {
          // Keep as string if not valid JSON
        }
        let groundTruth: unknown = item.groundTruth;
        if (item.groundTruth) {
          try {
            groundTruth = JSON.parse(item.groundTruth);
          } catch {
            // Keep as string if not valid JSON
          }
        }
        return { input, groundTruth };
      });

      return { items };
    } catch (error) {
      if (error instanceof MastraError) {
        throw new HTTPException(getHttpStatusForMastraError(error.id) as StatusCode, { message: error.message });
      }
      return handleError(error, 'Error generating dataset items');
    }
  },
});

// ============================================================================
// Failure Clustering
// ============================================================================

const 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.

For each cluster you identify, provide:
- A short, descriptive tag label (2-5 words, lowercase, hyphenated, e.g., "no-tool-usage", "hallucination")
- A description explaining the common failure pattern
- The IDs of items that belong to this cluster

Also 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.

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Read error.message in the response and the mapped status code to identify the originating MastraError domain id
  2. Fix the underlying cause (model config, credentials, request payload) that made the generation step throw
  3. If the message is opaque, enable server-side logging on the generation route to capture the full MastraError stack
  4. Ensure the client handles the mapped HTTP status rather than assuming 400/500

Example fix

// client sees opaque error
const res = await fetch('/api/datasets/generate', { method: 'POST', body });
if (!res.ok) console.error(await res.text());
// after — surface status + message deliberately
if (!res.ok) {
  const { message } = await res.json();
  throw new Error(`generate failed (${res.status}): ${message}`);
}
Defensive patterns

Strategy: try-catch

Validate before calling

// validate payload before calling
const body = { agentId, count };
if (!agentId || !Number.isInteger(count) || count <= 0) throw new Error('invalid generate request');

Type guard

function isMastraErrorBody(b: unknown): b is { message: string } {
  return typeof b === 'object' && b !== null && 'message' in b && typeof (b as any).message === 'string';
}

Try / catch

try {
  const res = await fetch('/api/datasets/generate', { method: 'POST', body: JSON.stringify(payload) });
  if (!res.ok) {
    const body = await res.json().catch(() => null);
    throw new Error(`generate failed (${res.status}): ${isMastraErrorBody(body) ? body.message : res.statusText}`);
  }
} catch (err) {
  logger.error({ err }, 'dataset generation failed');
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/a05931dc9175f7bb. Report an issue: GitHub.