fix(api): return Zod validation errors from public API routes (#708)

* fix(api): return Zod validation errors from public API routes

Public API handlers now surface ZodError details as 400 VALIDATION_ERROR
responses instead of generic 500 INTERNAL_ERROR payloads. Course import
services also rethrow ZodError so validation failures are not wrapped as
server errors.

Co-authored-by: Rotimi Best <[email protected]>

* refactor(utils): centralize course type values without db dependency

Define COURSE_TYPE_VALUES once in @cio/utils/constants and use it for
ZCourseType validation and the Drizzle COURSE_TYPE pgEnum. Removes the
circular @cio/utils -> @cio/db import while keeping course-import schemas
aligned with all four course types including PUBLIC.

Co-authored-by: Rotimi Best <[email protected]>

* fix(validation): default missing course metadata allowNewStudent to true

Courses stored without allowNewStudent in metadata failed structure export
validation. Align Zod preprocessing with runtime behavior where absent
values mean enrollments are open.

Co-authored-by: Rotimi Best <[email protected]>

* chore(db): drop unused COURSE_TYPE_VALUES re-export from schema

Co-authored-by: Rotimi Best <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Rotimi Best <[email protected]>
This commit is contained in:
Rotimi Best
2026-07-02 12:56:58 +01:00
committed by GitHub
co-authored by Rotimi Best Cursor Agent
parent a337363965
commit 0ed0e3864d
12 changed files with 166 additions and 30 deletions
@@ -0,0 +1,67 @@
import { describe, expect, it } from 'vitest';
import { z, ZodError } from 'zod';
import { Hono } from 'hono';
import { ZCourseType } from '@cio/utils/validation/course';
import { AppError, ErrorCodes, formatZodErrorMessage, handlePublicApiError } from '@api/utils/errors';
describe('formatZodErrorMessage', () => {
it('formats issue paths and messages', () => {
const schema = z.object({
course: z.object({
type: ZCourseType
})
});
try {
schema.parse({ course: { type: 'INVALID' } });
} catch (error) {
expect(error).toBeInstanceOf(ZodError);
expect(formatZodErrorMessage(error as ZodError)).toContain('course.type:');
}
});
});
describe('handlePublicApiError', () => {
const app = new Hono().get('/test', async (c) => {
try {
z.object({ allowNewStudent: z.boolean() }).parse({ allowNewStudent: undefined });
return c.json({ success: true });
} catch (error) {
return handlePublicApiError(c, error, 'Failed to fetch course structure');
}
});
it('returns validation details for ZodError instead of INTERNAL_ERROR', async () => {
const response = await app.request('/test');
const body = await response.json();
expect(response.status).toBe(400);
expect(body).toEqual({
success: false,
error: expect.stringContaining('allowNewStudent'),
code: ErrorCodes.VALIDATION_ERROR,
field: 'allowNewStudent'
});
});
it('delegates AppError handling to handleError', async () => {
const errorApp = new Hono().get('/test', async (c) => {
try {
throw new AppError('Course not found', ErrorCodes.COURSE_NOT_FOUND, 404);
} catch (error) {
return handlePublicApiError(c, error, 'Failed to fetch course');
}
});
const response = await errorApp.request('/test');
const body = await response.json();
expect(response.status).toBe(404);
expect(body).toEqual({
success: false,
error: 'Course not found',
code: ErrorCodes.COURSE_NOT_FOUND
});
});
});
+47
View File
@@ -1,5 +1,6 @@
import type { Context } from 'hono';
import type { ContentfulStatusCode } from 'hono/utils/http-status';
import { ZodError } from 'zod';
import { AppError, ErrorCodes, type ErrorCode } from '@cio/utils/errors';
@@ -19,6 +20,25 @@ export interface ErrorResponse {
field?: string;
}
function getZodErrorField(error: ZodError): string | undefined {
const firstIssue = error.issues[0];
if (!firstIssue || firstIssue.path.length === 0) {
return undefined;
}
return firstIssue.path.map(String).join('.');
}
export function formatZodErrorMessage(error: ZodError): string {
return error.issues
.map((issue) => {
const fieldPath = issue.path.length > 0 ? `${issue.path.map(String).join('.')}: ` : '';
return `${fieldPath}${issue.message}`;
})
.join('; ');
}
/**
* Handles errors consistently across all routes
* @param c - Hono context
@@ -70,3 +90,30 @@ export const handleError = (
500
);
};
/**
* Handles errors for public API routes, surfacing Zod validation failures
* as 400 responses instead of generic 500 INTERNAL_ERROR payloads.
*/
export const handlePublicApiError = (
c: Context,
error: unknown,
fallbackMessage: string = 'An unexpected error occurred',
fallbackCode?: string
) => {
if (error instanceof ZodError) {
console.error('Error in route:', error);
return c.json<ErrorResponse>(
{
success: false,
error: formatZodErrorMessage(error),
code: ErrorCodes.VALIDATION_ERROR,
field: getZodErrorField(error)
},
400
);
}
return handleError(c, error, fallbackMessage, fallbackCode);
};