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 <rotimi-best@users.noreply.github.com>

* 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 <rotimi-best@users.noreply.github.com>

* 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 <rotimi-best@users.noreply.github.com>

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

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>
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
+7 -7
View File
@@ -17,7 +17,7 @@ import {
import { Hono } from '@api/utils/hono';
import { automationKeyMiddleware } from '@api/middlewares/automation-key';
import { automationKeyScopesMiddleware } from '@api/middlewares/automation-key-scopes';
import { handleError } from '@api/utils/errors';
import { handlePublicApiError } from '@api/utils/errors';
import { describeRoute, validator } from 'hono-openapi';
const AudienceListResponse = {
@@ -87,7 +87,7 @@ export const v1AudienceRouter = new Hono()
200
);
} catch (error) {
return handleError(c, error, 'Failed to list audience members');
return handlePublicApiError(c, error, 'Failed to list audience members');
}
}
)
@@ -128,7 +128,7 @@ export const v1AudienceRouter = new Hono()
201
);
} catch (error) {
return handleError(c, error, 'Failed to create audience member');
return handlePublicApiError(c, error, 'Failed to create audience member');
}
}
)
@@ -168,7 +168,7 @@ export const v1AudienceRouter = new Hono()
200
);
} catch (error) {
return handleError(c, error, 'Failed to assign audience to courses');
return handlePublicApiError(c, error, 'Failed to assign audience to courses');
}
}
)
@@ -208,7 +208,7 @@ export const v1AudienceRouter = new Hono()
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch audience member');
return handlePublicApiError(c, error, 'Failed to fetch audience member');
}
}
)
@@ -249,7 +249,7 @@ export const v1AudienceRouter = new Hono()
200
);
} catch (error) {
return handleError(c, error, 'Failed to remove audience member');
return handlePublicApiError(c, error, 'Failed to remove audience member');
}
}
)
@@ -293,7 +293,7 @@ export const v1AudienceRouter = new Hono()
200
);
} catch (error) {
return handleError(c, error, 'Failed to update audience member');
return handlePublicApiError(c, error, 'Failed to update audience member');
}
}
);
+10 -10
View File
@@ -19,7 +19,7 @@ import {
import { Hono } from '@api/utils/hono';
import { automationKeyMiddleware } from '@api/middlewares/automation-key';
import { automationKeyScopesMiddleware } from '@api/middlewares/automation-key-scopes';
import { handleError } from '@api/utils/errors';
import { handlePublicApiError } from '@api/utils/errors';
import { describeRoute, validator } from 'hono-openapi';
const CoursesListResponse = {
@@ -76,7 +76,7 @@ export const v1CoursesRouter = new Hono()
200
);
} catch (error) {
return handleError(c, error, 'Failed to list courses');
return handlePublicApiError(c, error, 'Failed to list courses');
}
}
)
@@ -117,7 +117,7 @@ export const v1CoursesRouter = new Hono()
201
);
} catch (error) {
return handleError(c, error, 'Failed to create course');
return handlePublicApiError(c, error, 'Failed to create course');
}
}
)
@@ -157,7 +157,7 @@ export const v1CoursesRouter = new Hono()
200
);
} catch (error) {
return handleError(c, error, 'Failed to list course students');
return handlePublicApiError(c, error, 'Failed to list course students');
}
}
)
@@ -197,7 +197,7 @@ export const v1CoursesRouter = new Hono()
200
);
} catch (error) {
return handleError(c, error, 'Failed to export course');
return handlePublicApiError(c, error, 'Failed to export course');
}
}
)
@@ -237,7 +237,7 @@ export const v1CoursesRouter = new Hono()
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch course structure');
return handlePublicApiError(c, error, 'Failed to fetch course structure');
}
}
)
@@ -281,7 +281,7 @@ export const v1CoursesRouter = new Hono()
200
);
} catch (error) {
return handleError(c, error, 'Failed to update course structure');
return handlePublicApiError(c, error, 'Failed to update course structure');
}
}
)
@@ -321,7 +321,7 @@ export const v1CoursesRouter = new Hono()
200
);
} catch (error) {
return handleError(c, error, 'Failed to fetch course');
return handlePublicApiError(c, error, 'Failed to fetch course');
}
}
)
@@ -364,7 +364,7 @@ export const v1CoursesRouter = new Hono()
200
);
} catch (error) {
return handleError(c, error, 'Failed to update course');
return handlePublicApiError(c, error, 'Failed to update course');
}
}
)
@@ -404,7 +404,7 @@ export const v1CoursesRouter = new Hono()
200
);
} catch (error) {
return handleError(c, error, 'Failed to delete course');
return handlePublicApiError(c, error, 'Failed to delete course');
}
}
);
@@ -46,6 +46,7 @@ import {
import { getCourseOrganizationId } from '@cio/db/queries/tag';
import { assignCourseTagsByName } from '@api/services/tag';
import { generateSlug } from '@cio/utils/functions';
import { ZodError } from 'zod';
type DraftSummary = {
sectionCount: number;
@@ -537,7 +538,7 @@ export async function createCourseImportDraftService(orgId: string, profileId: s
sourceArtifacts: data.sourceArtifacts ?? data.draft.sourceReferences ?? []
});
} catch (error) {
if (error instanceof AppError) {
if (error instanceof AppError || error instanceof ZodError) {
throw error;
}
@@ -579,7 +580,7 @@ export async function getCourseImportStructureService(orgId: string, courseId: s
try {
return buildCourseStructureSnapshot(orgId, courseId);
} catch (error) {
if (error instanceof AppError) {
if (error instanceof AppError || error instanceof ZodError) {
throw error;
}
@@ -600,7 +601,7 @@ export async function getCourseImportDraftService(orgId: string, draftId: string
return draft;
} catch (error) {
if (error instanceof AppError) {
if (error instanceof AppError || error instanceof ZodError) {
throw error;
}
@@ -641,7 +642,7 @@ export async function updateCourseImportDraftService(orgId: string, draftId: str
return updated;
} catch (error) {
if (error instanceof AppError) {
if (error instanceof AppError || error instanceof ZodError) {
throw error;
}
@@ -845,7 +846,7 @@ export async function publishCourseImportDraftService(
localeCount: new Set(draft.lessonLanguages.map((item) => item.locale)).size
};
} catch (error) {
if (error instanceof AppError) {
if (error instanceof AppError || error instanceof ZodError) {
throw error;
}
@@ -1132,7 +1133,7 @@ export async function publishCourseImportDraftToExistingCourseService(
localeCount: new Set(draft.lessonLanguages.map((item) => item.locale)).size
};
} catch (error) {
if (error instanceof AppError) {
if (error instanceof AppError || error instanceof ZodError) {
throw error;
}
@@ -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);
};