feat(api): add global error handler with typed error classes

- Add AppError base class, ValidationError (400), NotFoundError (404)
- Add central error middleware in app.ts
- Remove inline safeParse error handling from controllers
- Replace plain Error throws with NotFoundError in gameService
This commit is contained in:
lila 2026-04-12 08:48:43 +02:00
parent dd6c2b0118
commit 48457936e8
7 changed files with 114 additions and 24 deletions

View file

@ -8,8 +8,8 @@ import type {
AnswerSubmission,
AnswerResult,
} from "@glossa/shared";
import { InMemoryGameSessionStore } from "../gameSessionStore/index.js";
import { NotFoundError } from "../errors/AppError.js";
const gameSessionStore = new InMemoryGameSessionStore();
@ -39,7 +39,6 @@ export const createGameSession = async (
const optionTexts = [correctAnswer.targetText, ...distractorTexts];
const shuffledTexts = shuffle(optionTexts);
const correctOptionId = shuffledTexts.indexOf(correctAnswer.targetText);
const options: AnswerOption[] = shuffledTexts.map((text, index) => ({
@ -64,6 +63,7 @@ export const createGameSession = async (
return { sessionId, questions };
};
const shuffle = <T>(array: T[]): T[] => {
const result = [...array];
for (let i = result.length - 1; i > 0; i--) {
@ -81,13 +81,13 @@ export const evaluateAnswer = async (
const session = await gameSessionStore.get(submission.sessionId);
if (!session) {
throw new Error(`Game session not found: ${submission.sessionId}`);
throw new NotFoundError(`Game session not found: ${submission.sessionId}`);
}
const correctOptionId = session.answers.get(submission.questionId);
if (correctOptionId === undefined) {
throw new Error(`Question not found: ${submission.questionId}`);
throw new NotFoundError(`Question not found: ${submission.questionId}`);
}
return {