如何在catch语句中获得适当的错误?

时间:2019-06-18 08:04:15

标签: reactjs typescript http fetch

我将ky.js用于HTTP。

这是我如何处理请求的示例:

enter image description here

在这里,我有一个问题,在catch语句中,我希望可以从Backend获取错误对象,但是却收到此错误:

HTTPError
    at _callee$ (webpack-internal:///./node_modules/ky/index.js:367:23)
    at tryCatch (webpack-internal:///./node_modules/regenerator-runtime/runtime.js:63:17)
    at Generator.invoke [as _invoke] (webpack-internal:///./node_modules/regenerator-runtime/runtime.js:282:22)
    at Generator.prototype.<computed> [as next] (webpack-internal:///./node_modules/regenerator-runtime/runtime.js:116:21)
    at asyncGeneratorStep (webpack-internal:///./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:5:24)
    at _next (webpack-internal:///./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:27:9)

我想这是一个webpack问题,但是我不知道如何解决。我正在使用TypeScript,这是我的tsconfig文件:

{
  "compilerOptions": {
    "target": "es2015",
    "module": "esnext",
    "jsx": "preserve",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true
  },
  "include": ["src", "types"]
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

此错误对象是由ky.js创建的客户端错误。 如果后端创建错误并将其打印到响应正文,则您需要读取响应正文以获取错误消息。我不知道ky.js,但我知道是这样的:

error.response.text.then(text => console.log(text));