- Created .gitignore to exclude build outputs, logs, and environment files. - Added nuxt.config.ts for project configuration, enabling Tailwind CSS and Pinia modules. - Initialized package.json with scripts for development and production, and added necessary dependencies. - Generated pnpm-lock.yaml for dependency management. - Created README.md with setup instructions and development guidelines. - Implemented server API examples in server/api/ directory, demonstrating various use cases. - Added middleware for logging requests and responses. - Included example Vue components and pages for server API interaction. - Established basic project structure for Nuxt 4 application development.
66 lines
1.8 KiB
TypeScript
66 lines
1.8 KiB
TypeScript
/**
|
|
* 케이스 6: createError로 에러 처리
|
|
*
|
|
* - URL: GET /api/06-error-handling?type=notfound|forbidden|custom
|
|
* - createError(): HTTP 에러 응답 생성 (H3Error 던지기)
|
|
* - fatal: true → 에러 페이지로 이동 (CSR 환경)
|
|
* - data: 에러 응답 본문에 추가 데이터 포함 가능
|
|
*
|
|
* 클라이언트에서의 에러 처리:
|
|
* const { data, error } = await useFetch('/api/06-error-handling?type=notfound')
|
|
* if (error.value) console.log(error.value.statusCode) // 404
|
|
*/
|
|
|
|
export default defineEventHandler((event) => {
|
|
const { type } = getQuery(event);
|
|
|
|
if (type === "notfound") {
|
|
// 가장 일반적인 패턴
|
|
throw createError({
|
|
statusCode: 404,
|
|
statusMessage: "리소스를 찾을 수 없습니다.",
|
|
});
|
|
}
|
|
|
|
if (type === "forbidden") {
|
|
throw createError({
|
|
statusCode: 403,
|
|
statusMessage: "접근 권한이 없습니다.",
|
|
// data: 클라이언트에서 error.value.data로 접근 가능
|
|
data: { required: "admin", current: "user" },
|
|
});
|
|
}
|
|
|
|
if (type === "custom") {
|
|
throw createError({
|
|
statusCode: 422,
|
|
statusMessage: "유효성 검사 실패",
|
|
data: {
|
|
fields: {
|
|
email: "올바른 이메일 형식이 아닙니다.",
|
|
age: "18세 이상이어야 합니다.",
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
// 예기치 않은 에러는 try/catch로 처리
|
|
try {
|
|
// 외부 API 호출 등 예시
|
|
const result = riskyOperation();
|
|
return { result };
|
|
} catch (err) {
|
|
// 내부 에러는 500으로 래핑
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: "서버 내부 오류",
|
|
cause: err,
|
|
});
|
|
}
|
|
});
|
|
|
|
function riskyOperation(): string {
|
|
if (Math.random() > 0.5) throw new Error("랜덤 오류 발생!");
|
|
return "성공!";
|
|
}
|