@@ -12,6 +12,7 @@ export async function POST(request: Request) {
1212 }
1313
1414 const baseUrl = body . baseUrl . replace ( / \/ $ / , '' )
15+ const url = `${ baseUrl } /v1/sandboxes`
1516 const apiBody : Record < string , unknown > = {
1617 profile : body . profile || 'small' ,
1718 ttl_seconds : body . ttlSeconds || 3600 ,
@@ -20,23 +21,33 @@ export async function POST(request: Request) {
2021 apiBody . image = body . image
2122 }
2223
23- const res = await fetch ( `${ baseUrl } /v1/sandboxes` , {
24- method : 'POST' ,
25- headers : {
26- 'Authorization' : `Bearer ${ body . apiKey } ` ,
27- 'Content-Type' : 'application/json' ,
28- 'Accept' : 'application/json' ,
29- } ,
30- body : JSON . stringify ( apiBody ) ,
31- } )
24+ let res : Response
25+ try {
26+ res = await fetch ( url , {
27+ method : 'POST' ,
28+ headers : {
29+ 'Authorization' : `Bearer ${ body . apiKey } ` ,
30+ 'Content-Type' : 'application/json' ,
31+ 'Accept' : 'application/json' ,
32+ } ,
33+ body : JSON . stringify ( apiBody ) ,
34+ } )
35+ } catch ( fetchErr ) {
36+ const detail = fetchErr instanceof Error ? fetchErr . message : 'Unknown fetch error'
37+ return NextResponse . json (
38+ { error : `Failed to connect to ${ url } : ${ detail } ` } ,
39+ { status : 502 } ,
40+ )
41+ }
3242
3343 const text = await res . text ( )
3444 let data : Record < string , unknown >
3545 try {
3646 data = JSON . parse ( text ) as Record < string , unknown >
3747 } catch {
48+ const preview = text . length > 0 ? text . slice ( 0 , 500 ) : '(empty body)'
3849 return NextResponse . json (
39- { error : `API returned ${ res . status } : ${ text . slice ( 0 , 500 ) } ` } ,
50+ { error : `API returned ${ res . status } with non-JSON response : ${ preview } ` } ,
4051 { status : res . status || 500 } ,
4152 )
4253 }
0 commit comments