当”Got”包由于坏的JSON而崩溃时,如何获取响应文本?

huangapple go评论59阅读模式
英文:

How to get response text when Got package crashes with bad JSON?

问题

抱歉,代码部分不要翻译。以下是翻译好的部分:

"Hi. I have an API endpoint that normally returns JSON, but sometimes there's an error and it prints something that breaks the JSON. Got just crashes with 'Unexpected token < in JSON at position 0'. How do I get the actual faulty text here?"

英文:
import got from &quot;got&quot;;

try {
    await got(&#39;https://google.com&#39;).json();
} catch (e) {
    console.log(e);
    // how do I get response text here?
}

Hi. I have an API endpoint that normally returns JSON, but sometimes there's an error and it prints something that breaks the JSON. Got just crashes with Unexpected token &lt; in JSON at position 0. How do I get the actual faulty text here?

答案1

得分: 1

根据got的文档,ParseError 包括一个 response 属性,您可以使用它来检索原始响应。

import got, { ParseError } from "got";

try {
    await got('https://google.com').json();
} catch (e) {
    console.log(e);
    // 在这里如何获取响应文本?
    if(e instanceof ParseError)
    {
        console.log(e.response.body);
    }
}
英文:

As stated in got's documentation, ParseError includes a response property, which you can use to retrieve the raw response.

import got, { ParseError } from &quot;got&quot;;

try {
    await got(&#39;https://google.com&#39;).json();
} catch (e) {
    console.log(e);
    // how do I get response text here?
    if(e instanceof ParseError)
    {
        console.log(e.response.body);
    }
}

huangapple
  • 本文由 发表于 2023年7月10日 15:08:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651418.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定