Skip to content

Commit d2febc6

Browse files
authored
Merge pull request #4 from Emlembow/claude/issue-3-20250610_170119
fix: Enhanced error handling for 503 API service unavailable errors
2 parents 00d68cd + ed2f350 commit d2febc6

File tree

3 files changed

+107
-22
lines changed

3 files changed

+107
-22
lines changed

app/api/chat/route.ts

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,28 @@ export async function POST(request: NextRequest) {
2929
})
3030
}
3131

32-
// Get system prompt
33-
const systemPrompt = await buildSystemPrompt()
32+
// Get system prompt with enhanced error handling
33+
let systemPrompt: string
34+
try {
35+
console.log('Attempting to build system prompt...')
36+
systemPrompt = await buildSystemPrompt()
37+
console.log('System prompt built successfully')
38+
} catch (error) {
39+
console.error('Failed to build system prompt:', error)
40+
return new NextResponse(
41+
JSON.stringify({
42+
error: "Service temporarily unavailable",
43+
details: `Failed to build system prompt: ${error instanceof Error ? error.message : 'Unknown error'}`,
44+
debug: process.env.NODE_ENV === 'development' ? {
45+
stack: error instanceof Error ? error.stack : 'No stack trace available'
46+
} : undefined
47+
}),
48+
{
49+
status: 503,
50+
headers: { "Content-Type": "application/json" },
51+
},
52+
)
53+
}
3454

3555
// Initialize OpenAI client
3656
const openai = new OpenAI({
@@ -79,13 +99,23 @@ export async function POST(request: NextRequest) {
7999

80100
} catch (error) {
81101
console.error("Error processing chat request:", error)
102+
103+
// Determine if this is a system prompt error or other error
104+
const isSystemPromptError = error instanceof Error && error.message.includes('system prompt')
105+
const statusCode = isSystemPromptError ? 503 : 500
106+
82107
return new NextResponse(
83108
JSON.stringify({
84-
error: "Service temporarily unavailable",
109+
error: isSystemPromptError ? "Service temporarily unavailable" : "Internal server error",
85110
details: error instanceof Error ? error.message : "Unknown error",
111+
errorType: isSystemPromptError ? "system_prompt_error" : "general_error",
112+
debug: process.env.NODE_ENV === 'development' ? {
113+
stack: error instanceof Error ? error.stack : 'No stack trace available',
114+
timestamp: new Date().toISOString()
115+
} : undefined
86116
}),
87117
{
88-
status: 503,
118+
status: statusCode,
89119
headers: { "Content-Type": "application/json" },
90120
},
91121
)

lib/content.ts

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,30 @@ export type Education = {
5757
// Helper function to read directory contents
5858
const readDirectory = (dir: string) => {
5959
const directory = path.join(process.cwd(), dir)
60-
return fs.readdirSync(directory)
60+
try {
61+
console.log(`Reading directory: ${directory}`)
62+
const files = fs.readdirSync(directory)
63+
console.log(`Successfully read directory ${dir} with ${files.length} files`)
64+
return files
65+
} catch (error) {
66+
console.error(`Failed to read directory ${dir}:`, error)
67+
throw new Error(`Cannot read directory ${dir}: ${error instanceof Error ? error.message : 'Unknown error'}`)
68+
}
6169
}
6270

6371
// Helper function to read and parse markdown file
6472
const readMarkdownFile = (filePath: string) => {
6573
const fullPath = path.join(process.cwd(), filePath)
66-
const fileContents = fs.readFileSync(fullPath, "utf8")
67-
return matter(fileContents)
74+
try {
75+
console.log(`Reading markdown file: ${fullPath}`)
76+
const fileContents = fs.readFileSync(fullPath, "utf8")
77+
const parsed = matter(fileContents)
78+
console.log(`Successfully parsed markdown file: ${filePath}`)
79+
return parsed
80+
} catch (error) {
81+
console.error(`Failed to read markdown file ${filePath}:`, error)
82+
throw new Error(`Cannot read file ${filePath}: ${error instanceof Error ? error.message : 'Unknown error'}`)
83+
}
6884
}
6985

7086
// Get profile information

lib/system-prompt.ts

Lines changed: 54 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -121,29 +121,51 @@ const buildSystemPromptFromTemplate = async (templateContent: string, data: {
121121
// System prompt builder function
122122
export const buildSystemPrompt = cache(async (): Promise<string> => {
123123
try {
124+
console.log('Starting system prompt build process...')
125+
124126
// Read the main template file
125127
const templatePath = path.join(process.cwd(), 'content/system-prompt.md')
126-
const templateContent = fs.readFileSync(templatePath, 'utf8')
128+
console.log(`Reading main template from: ${templatePath}`)
129+
130+
let templateContent: string
131+
try {
132+
templateContent = fs.readFileSync(templatePath, 'utf8')
133+
console.log(`Successfully read main template (${templateContent.length} characters)`)
134+
} catch (error) {
135+
console.error(`Failed to read main template file: ${error}`)
136+
throw new Error(`Failed to read system prompt template: ${error instanceof Error ? error.message : 'Unknown error'}`)
137+
}
127138

128139
// Read the additional system prompt file if it exists
129140
const additionalTemplatePath = path.join(process.cwd(), 'content/system-prompt-extended.md')
130141
let additionalContent = ''
142+
console.log(`Checking for extended template at: ${additionalTemplatePath}`)
131143
try {
132144
additionalContent = fs.readFileSync(additionalTemplatePath, 'utf8')
145+
console.log(`Successfully read extended template (${additionalContent.length} characters)`)
133146
} catch (error) {
134147
console.log('No extended system prompt file found, continuing with base content only')
135148
}
136149

137-
// Fetch all content
138-
const [profile, about, education, experiences, references, blogPosts, projects] = await Promise.all([
139-
getProfileInfo(),
140-
getAboutContent(),
141-
getEducation(),
142-
getExperiences(),
143-
getReferences(),
144-
getBlogPosts(),
145-
getProjects(),
146-
])
150+
// Fetch all content with individual error handling
151+
console.log('Fetching all content sources...')
152+
let profile, about, education, experiences, references, blogPosts, projects
153+
154+
try {
155+
[profile, about, education, experiences, references, blogPosts, projects] = await Promise.all([
156+
getProfileInfo(),
157+
getAboutContent(),
158+
getEducation(),
159+
getExperiences(),
160+
getReferences(),
161+
getBlogPosts(),
162+
getProjects(),
163+
])
164+
console.log('Successfully fetched all content sources')
165+
} catch (error) {
166+
console.error(`Failed to fetch content sources: ${error}`)
167+
throw new Error(`Failed to load content: ${error instanceof Error ? error.message : 'Unknown error'}`)
168+
}
147169

148170
// Format work experience
149171
const workExperience = experiences.map((exp, index) => `
@@ -256,18 +278,35 @@ ${post.content.replace(/<[^>]*>/g, '').slice(0, 500).trim()}...
256278
}
257279

258280
// Build the main system prompt
259-
const mainPrompt = await buildSystemPromptFromTemplate(templateContent, templateData)
281+
console.log('Building main system prompt from template...')
282+
let mainPrompt: string
283+
try {
284+
mainPrompt = await buildSystemPromptFromTemplate(templateContent, templateData)
285+
console.log(`Successfully built main prompt (${mainPrompt.length} characters)`)
286+
} catch (error) {
287+
console.error(`Failed to build main prompt from template: ${error}`)
288+
throw new Error(`Template processing failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
289+
}
260290

261291
// Build and append extended content if available
262292
let finalPrompt = mainPrompt
263293
if (additionalContent) {
264-
const extendedPrompt = await buildSystemPromptFromTemplate(additionalContent, templateData)
265-
finalPrompt = `${mainPrompt}\n\n## EXTENDED CONTEXT\n${extendedPrompt}`
294+
console.log('Processing extended template content...')
295+
try {
296+
const extendedPrompt = await buildSystemPromptFromTemplate(additionalContent, templateData)
297+
finalPrompt = `${mainPrompt}\n\n## EXTENDED CONTEXT\n${extendedPrompt}`
298+
console.log(`Successfully built extended prompt (${finalPrompt.length} total characters)`)
299+
} catch (error) {
300+
console.error(`Failed to process extended template: ${error}`)
301+
console.log('Continuing with main prompt only')
302+
}
266303
}
267304

305+
console.log('System prompt build completed successfully')
268306
return finalPrompt
269307
} catch (error) {
270308
console.error('Error building system prompt:', error)
271-
throw new Error('Failed to build system prompt')
309+
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'
310+
throw new Error(`Failed to build system prompt: ${errorMessage}`)
272311
}
273312
})

0 commit comments

Comments
 (0)