From 340c9d6101a7531b2d167ed59ac0ba56ae4b8f7c Mon Sep 17 00:00:00 2001 From: bholmesdev Date: Tue, 23 Apr 2024 14:34:26 -0400 Subject: [PATCH] feat: basic validationError class --- packages/actions/src/runtime/utils.ts | 16 ++++++++++++++++ packages/actions/src/virtual.ts | 8 +++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/actions/src/runtime/utils.ts b/packages/actions/src/runtime/utils.ts index 73a2c2b1ec..24048c870c 100644 --- a/packages/actions/src/runtime/utils.ts +++ b/packages/actions/src/runtime/utils.ts @@ -1,5 +1,6 @@ import type { APIContext } from 'astro'; import { AsyncLocalStorage } from 'node:async_hooks'; +import type { ZodError } from 'zod'; export const ApiContextStorage = new AsyncLocalStorage(); @@ -18,3 +19,18 @@ export async function getAction(pathKeys: string[]): Promise { } return actionLookup; } + +export class ActionError extends Error { + constructor(message: string) { + super(message); + } +} + +export class ValidationError extends ActionError { + error: ZodError; + + constructor(error: ZodError) { + super('Failed to validate'); + this.error = error; + } +} diff --git a/packages/actions/src/virtual.ts b/packages/actions/src/virtual.ts index 4aeaff9141..a43f14976d 100644 --- a/packages/actions/src/virtual.ts +++ b/packages/actions/src/virtual.ts @@ -1,3 +1,5 @@ +import { ValidationError } from './runtime/utils.js'; + function toActionProxy( actionCallback = {}, aggregatedPath = '/_actions/' @@ -21,7 +23,11 @@ function toActionProxy( body, headers, }); - return res.json(); + const json = await res.json(); + if (res.status === 400) { + throw new ValidationError(json); + } + return json; } action.toString = () => path; // recurse to construct queries for nested object paths