4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Nuxt3】APIのエラーをNuxtのレスポンスに引き継ぐ方法

Last updated at Posted at 2023-07-13

結論

userAsyncData のレスポンスの errorcreateError の引数に指定して
throw createError(error.value) とすればよい。

<template>
  <h1>{{ healthcheck?.status }}</h1>
</template>

<script setup lang="ts">
interface Healthcheck {
  status: string
}
const { data: healthcheck, error, status } = await useAsyncData<Healthcheck>(
  "healthcheck",
  () => {
    return $fetch("/healthcheck", {method: "GET"})
  }
)

if (error.value) {
  console.error(error.value)
  throw createError(error.value)
}
</script>

こんな感じで、APIの404エラーをそのままNuxtのレスポンスに引き継ぐことができる。

スクリーンショット 2023-07-13 213447.png

ちなみに createError は下記のように任意のステータスコードとエラーメッセージを指定することもできる。

throw createError({ statusCode: 404, statusMessage: 'Page Not Found' })

参考

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?