Skip to content

Commit 20e0b8e

Browse files
committed
gravity api: if !ok, don't require json response
1 parent 4452889 commit 20e0b8e

File tree

1 file changed

+31
-9
lines changed

1 file changed

+31
-9
lines changed

web/src/app/api/v1/ads/_post.ts

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -136,11 +136,11 @@ export async function postAds(params: {
136136
// Build device object for Gravity API
137137
const device = clientIp
138138
? {
139-
ip: clientIp,
140-
...(deviceInfo?.os ? { os: deviceInfo.os } : {}),
141-
...(deviceInfo?.timezone ? { timezone: deviceInfo.timezone } : {}),
142-
...(deviceInfo?.locale ? { locale: deviceInfo.locale } : {}),
143-
}
139+
ip: clientIp,
140+
...(deviceInfo?.os ? { os: deviceInfo.os } : {}),
141+
...(deviceInfo?.timezone ? { timezone: deviceInfo.timezone } : {}),
142+
...(deviceInfo?.locale ? { locale: deviceInfo.locale } : {}),
143+
}
144144
: undefined
145145

146146
try {
@@ -176,17 +176,39 @@ export async function postAds(params: {
176176
return NextResponse.json({ ad: null }, { status: 200 })
177177
}
178178

179-
// Now safe to parse JSON body
180-
const ads = await response.json()
181-
179+
// Check response.ok BEFORE parsing JSON to handle HTML error pages gracefully
182180
if (!response.ok) {
181+
// Try to get response body for logging, but don't fail if it's not JSON
182+
let errorBody: unknown
183+
try {
184+
const contentType = response.headers.get('content-type') ?? ''
185+
if (contentType.includes('application/json')) {
186+
errorBody = await response.json()
187+
} else {
188+
// Likely an HTML error page from load balancer/CDN
189+
errorBody = await response.text()
190+
}
191+
} catch {
192+
errorBody = 'Unable to parse error response'
193+
}
183194
logger.error(
184-
{ request: requestBody, response: ads, status: response.status },
195+
{ request: requestBody, response: errorBody, status: response.status },
185196
'[ads] Gravity API returned error',
186197
)
187198
return NextResponse.json({ ad: null }, { status: 200 })
188199
}
189200

201+
// Now safe to parse JSON body since response.ok is true
202+
const ads = await response.json()
203+
204+
if (!Array.isArray(ads) || ads.length === 0) {
205+
logger.debug(
206+
{ request: requestBody, response: ads, status: response.status },
207+
'[ads] No ads returned from Gravity API',
208+
)
209+
return NextResponse.json({ ad: null }, { status: 200 })
210+
}
211+
190212
const ad = ads[0]
191213

192214
const payout = ad.payout || DEFAULT_PAYOUT

0 commit comments

Comments
 (0)