feat(validation): ValidationError → 422 with source + issues (before HttpError)
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
3 files changed
+40
-3
No files matched your search
@@ -1,3 +1,5 @@
|
||||
import type { StandardIssue } from './standard-schema';
|
||||
|
||||
export class HttpError extends Error {
|
||||
constructor(readonly status: number, message?: string, readonly body?: unknown) {
|
||||
super(message ?? `HTTP ${status}`);
|
||||
@@ -21,6 +23,12 @@ export class Redirect extends HttpError {
|
||||
constructor(readonly location: string) { super(302); }
|
||||
}
|
||||
|
||||
export class ValidationError extends HttpError {
|
||||
constructor(public issues: StandardIssue[], public source: string) {
|
||||
super(422, 'Validation failed');
|
||||
}
|
||||
}
|
||||
|
||||
export function isHttpError(e: unknown): e is HttpError {
|
||||
return e instanceof HttpError;
|
||||
}
|
||||
+13
-1
@@ -1,5 +1,6 @@
|
||||
import { isHttpError, Redirect } from './signals';
|
||||
import { isHttpError, Redirect, ValidationError } from './signals';
|
||||
import type { TransformerFn } from './metadata';
|
||||
import { flattenPath } from './standard-schema';
|
||||
|
||||
export const JsonTransformer: TransformerFn = (value) => ({
|
||||
status: 200,
|
||||
@@ -8,6 +9,17 @@ export const JsonTransformer: TransformerFn = (value) => ({
|
||||
});
|
||||
|
||||
export function errorToResponse(e: unknown): { status: number; headers: Record<string, string>; body: string } {
|
||||
if (e instanceof ValidationError) {
|
||||
return {
|
||||
status: 422,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
error: 'Validation failed',
|
||||
source: e.source,
|
||||
issues: e.issues.map((i) => ({ path: flattenPath(i), message: i.message })),
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (isHttpError(e)) {
|
||||
const headers: Record<string, string> = { 'content-type': 'application/json' };
|
||||
if (e instanceof Redirect) headers.location = e.location;
|
||||
|
||||
Reference in new issue
Block a user