Improve HTML response detection in NIP-95 upload API
**Motivations:** - Better error handling when endpoints return HTML error pages instead of JSON - Provide clearer error messages to users **Root causes:** - Some NIP-95 endpoints (e.g., nostrimg.com) return HTML error pages instead of JSON - Current error handling only catches JSON parse errors without detecting HTML responses - Users get confusing error messages about JSON parsing when the real issue is an HTML response **Correctifs:** - Added HTML detection before JSON parsing - Extract error message from HTML title or h1 tags when possible - Provide clearer error message indicating HTML response instead of JSON - Improved error logging with HTML body preview **Evolutions:** - None **Pages affectées:** - pages/api/nip95-upload.ts
This commit is contained in:
parent
32b33d56a1
commit
c7f8d301d5
@ -243,6 +243,29 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
})
|
||||
}
|
||||
|
||||
// Check if response is HTML (error page) instead of JSON
|
||||
const trimmedBody = response.body.trim()
|
||||
const isHtml = trimmedBody.startsWith('<!DOCTYPE') || trimmedBody.startsWith('<html') || trimmedBody.startsWith('<!')
|
||||
|
||||
if (isHtml) {
|
||||
// Try to extract error message from HTML if possible
|
||||
const titleMatch = response.body.match(/<title[^>]*>([^<]+)<\/title>/i)
|
||||
const h1Match = response.body.match(/<h1[^>]*>([^<]+)<\/h1>/i)
|
||||
const errorText = titleMatch?.[1] || h1Match?.[1] || 'HTML error page returned'
|
||||
|
||||
console.error('NIP-95 proxy HTML response error:', {
|
||||
targetEndpoint,
|
||||
finalUrl: currentUrl.toString(),
|
||||
status: response.statusCode,
|
||||
errorText,
|
||||
bodyPreview: response.body.substring(0, 200),
|
||||
})
|
||||
|
||||
return res.status(500).json({
|
||||
error: `Endpoint returned an HTML error page instead of JSON. The endpoint may be unavailable or the URL may be incorrect. Error: ${errorText}`,
|
||||
})
|
||||
}
|
||||
|
||||
let result: unknown
|
||||
try {
|
||||
result = JSON.parse(response.body)
|
||||
@ -254,7 +277,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
bodyPreview: response.body.substring(0, 100),
|
||||
})
|
||||
return res.status(500).json({
|
||||
error: `Invalid upload response: ${errorMessage}`,
|
||||
error: `Invalid upload response: ${errorMessage}. The endpoint may not be a valid NIP-95 upload endpoint.`,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user