Nuxt3 通过 server/api/someCall 调用远程 api 时捕获错误

问题描述 投票:0回答:2

在我的第一个 Nuxt3 应用程序中,我尝试在

server/api
文件夹中设置外部 API 请求。

通过以下配置,请求成功后一切都很好。但是,我正在努力确定如何恢复错误响应。

我的

<TestApi></TestApi>
文件:

<template>
  <div>
    <div>Check developer console!</div>
  </div>
</template>

<script setup>

onMounted(async () => {
  const company = await $fetch('/api/getCompany', {
    async onRequestError({ request, options, error }) {
      // Log error
      console.log('[fetch request error]', request, error)
    }
  })


  console.log(company)
})

// const config = useRuntimeConfig()
// console.log('Runtime config:', config.apiBase)
// if (process.server) {
//   console.log('API secret:', config.apiSecret)
// }
</script>

我的

server/api/getCompany.ts
文件:

export default defineEventHandler(async (event) => {
  //Defined in nuxt.config.ts
  const config = useRuntimeConfig()
  const baseURL = config.public.apiBase

  const company = await $fetch(baseURL+'/company?bookingAppApiKey='+config.apiSecret, {
    async onRequestError({ request, options, error }) {
      // Log error
      console.log('[fetch request error]', request, error)
    }
  })

  return company
})

我想从

/server/api/getCompany.ts
中获取远程 URL 请求响应代码和消息,以便在
<TestApi>
中处理。

vuejs3 fetch-api nuxtjs3
2个回答
1
投票

$fetch
会抛出错误,基于此您可以自定义服务器路由返回的错误消息并添加任意信息:

// ~/server/api/getCompany.ts

import { FetchError } from 'ohmyfetch'

export default defineEventHandler(async () => {
  const url = 'https://google.com/404' // or: baseURL+'/company?bookingAppApiKey='+config.apiSecret

  try {
    return await $fetch(url)
  } catch (err) {
    throw createError({
      statusCode: 444,
      message: 'Oh no!',
      data: {
        statusCode: (err as FetchError).response?.status,
        responseBody: (err as FetchError).data,
      },
    })
  }
})

(我的回答显然可以改进类型处理。)

同样,您可以捕获组件中的错误并根据需要进行处理。

请三思而后行,是否真的想公开服务器响应中的信息。这可能包含机密数据,例如您的 API 秘密。一般来说,最好将其记录在服务器端,但不要在 API 响应中公开公开。


0
投票

对于任何遇到这个问题的人,这篇类似的文章包含当前在 Nuxt 3 中使用 useFetch 时处理和返回错误的解决方案处理 Nuxt 3 useFetch 上的错误,因为 ohmyfetch 不再是你可以访问的东西FetchError 类型。

这不仅从我的服务器 API 返回了错误信息,还从我调用的第 3 方 API 返回了错误信息,使我能够准确地知道应用程序外部发生了什么。此方法将信息直接带回客户端,以便根据需要显示/记录。

© www.soinside.com 2019 - 2024. All rights reserved.