How do I catch the full error thrown after an API call

Hi all,

I’m relatively new to JS and gpt-API. I have a NodeJS javascript script file on macOS that essentially reads a text file, breaks it down to paragraphs, sends each para to the server via the completion API along with a prompt to do something with it, and then reconstructs a file with new content.

All that is straightforward and it works well (for most parts). However, sometimes, the API seems to crap and throws an error (the reasons are different, like 400, or length or whatever else, and that’s fine) that looks like below in the end:

`
[Symbol(kCapture)]: false,
[Symbol(kBytesWritten)]: 0,
[Symbol(kEndCalled)]: true,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] {
accept: [ ‘Accept’, ‘application/json, text/plain, /’ ],
‘content-type’: [ ‘Content-Type’, ‘application/json’ ],
‘user-agent’: [ ‘User-Agent’, ‘OpenAI/NodeJS/3.3.0’ ],
authorization: [
‘Authorization’,
‘Bearer ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■b0rby0jq’
],
‘content-length’: [ ‘Content-Length’, 8325 ],
host: [ ‘Host’, 'xxxx ]
},
[Symbol(kUniqueHeaders)]: null
},
data: {
error: {
code: 502,
message: ‘Bad gateway.’,
param: null,
type: ‘cf_bad_gateway’
}
}
},
isAxiosError: true,
toJSON: [Function: toJSON]
}

`
I can’t figure out how to capture this so I can just print out the data.error.message. If I place the chat completion API in a try catch and print the error, I just see a short message where this error often contains lot more details (e.g., your tokens were X length but the model supports only Y, instead of ‘400 error’).

How do I catch this error object? because the

`
try {
…completion call…
} catch (err) {
console.log(err)
}

`

isn’t doing it. I’m probably missing something basic but I’m not skilled enough to figure it out.

Thank you!

Welcome to the forum!

It seems you are getting back an

error: {
    code: 502,
    message: ‘Bad gateway.’,
    param: null,
    type: ‘cf_bad_gateway’
}

So you can extract the error state, if it’s not a code 2?? then you know you hit a problem and deal with it.

3 Likes