createError

创建一个包含附加元数据的错误对象。

你可以使用此函数创建包含附加元数据的错误对象。它可用于应用的 Vue 和 Nitro 部分,并且旨在被抛出。

¥You can use this function to create an error object with additional metadata. It is usable in both the Vue and Nitro portions of your app, and is meant to be thrown.

参数

¥Parameters

  • errstring | { cause, data, message, name, stack, statusCode, statusMessage, fatal }

你可以将字符串或对象传递给 createError 函数。如果你传递一个字符串,它将被用作错误 message,而 statusCode 将默认为 500。如果传递一个对象,则可以设置错误的多个属性,例如 statusCodemessage 和其他错误属性。

¥You can pass either a string or an object to the createError function. If you pass a string, it will be used as the error message, and the statusCode will default to 500. If you pass an object, you can set multiple properties of the error, such as statusCode, message, and other error properties.

Vue 应用中

¥In Vue App

如果你在使用 createError 创建时抛出错误:

¥If you throw an error created with createError:

  • 在服务器端,它会触发一个全屏错误页面,你可以使用 clearError 清除该页面。
  • 在客户端,它会抛出一个非致命错误供你处理。如果你需要触发全屏错误页面,可以通过设置 fatal: true 来实现。

示例

¥Example

pages/movies/[slug].vue
<script setup lang="ts">
const route = useRoute()
const { data } = await useFetch(`/api/movies/${route.params.slug}`)
if (!data.value) {
  throw createError({ statusCode: 404, statusMessage: 'Page Not Found' })
}
</script>

API 路由中

¥In API Routes

使用 createError 触发服务器 API 路由中的错误处理。

¥Use createError to trigger error handling in server API routes.

示例

¥Example

server/api/error.ts
export default eventHandler(() => {
  throw createError({
    statusCode: 404,
    statusMessage: 'Page Not Found'
  })
})

在 API 路由中,建议通过传递带有短 statusMessage 的对象来使用 createError,因为它可以在客户端访问。否则,通过 API 路由传递给 createErrormessage 将不会传播到客户端。或者,你可以使用 data 属性将数据传回客户端。无论如何,请始终考虑避免将动态用户输入添加到消息中,以避免潜在的安全问题。

¥In API routes, using createError by passing an object with a short statusMessage is recommended because it can be accessed on the client side. Otherwise, a message passed to createError on an API route will not propagate to the client. Alternatively, you can use the data property to pass data back to the client. In any case, always consider avoiding to put dynamic user input to the message to avoid potential security issues.

Read more in Docs > Getting Started > Error Handling.