错误处理
¥Error Handling
通过抛出 HTTPError 来发送错误。
¥Send errors by throwing an HTTPError.
H3 捕获 请求生命周期 期间所有可能的错误。
¥H3 captures all possible errors during request lifecycle.
HTTPError
你可以使用 HTTPError
以不同的语法创建和抛出 HTTP 错误。
¥You can create and throw HTTP errors using HTTPError
with different syntaxes.
import { HTTPError } from "h3";
app.get("/error", (event) => {
// Using message and details
throw new HTTPError("Invalid user input", { status: 400 });
// Using HTTPError.status(code)
throw HTTPError.status(400, "Bad Request");
// Using single pbject
throw new HTTPError({
status: 400,
statusText: "Bad Request",
message: "Invalid user input",
data: { field: "email" },
body: { date: new Date().toJSON() },
headers: {},
});
});
这将以 400 - Bad Request
状态码和以下 JSON 响应结束请求:
¥This will end the request with 400 - Bad Request
status code and the following JSON response:
{
"date": "2025-06-05T04:20:00.0Z",
"status": 400,
"statusText": "Bad Request",
"message": "Invalid user input",
"data": {
"field": "email"
}
}
HTTPError
字段
¥HTTPError
Fields
status
:HTTP 状态码范围为 200-599。statusText
:要在响应标头中发送的 HTTP 状态文本。message
:错误消息将包含在 JSON 正文中。data
:将在错误 JSON 正文中的data
键下附加额外的数据。body
:在错误 JSON 主体中附加了额外的顶层属性。headers
:将在错误响应中发送额外的 HTTP 标头。cause
:导致此错误的原始错误对象,可用于跟踪和调试。unhandled
:指示错误是否因未知原因而引发。参见 未处理的错误。
错误
statusText
应简短(最多 512 到 1024 个字符),并且仅包含制表符、空格或可见 ASCII 字符和扩展字符(字节值 128-255)。扩展消息的 JSON 正文中优先使用 message
。¥!IMPORTANT
Error statusText
should be short (max 512 to 1024 characters) and only include tab, spaces or visible ASCII characters and extended characters (byte value 128–255). Prefer message
in JSON body for extended message.未处理的错误
¥Unhandled Errors
在未使用 HTTPError
的情况下调用 请求生命周期 时发生的任何错误都将被视为未处理的错误。
¥Any error that occurs during calling request lifecycle without using HTTPError
will be processed as an unhandled error.
app.get("/error", (event) => {
// This will cause an unhandled error.
throw new Error("Something went wrong");
});
为了增强安全性,H3 在 JSON 响应中隐藏了未处理错误的某些字段(
data
、body
、stack
和 message
)。¥!TIP
For enhanced security, H3 hides certain fields of unhandled errors (data
, body
, stack
and message
) in JSON response.捕获错误
¥Catching Errors
使用全局 onError
钩子:
¥Using global onError
hook:
import { H3, onError } from "h3";
// Globally handling errors
const app = new H3({
onError: (error) => {
console.error(error);
},
});
使用 onError
中间件 捕获错误。
¥Using onError
middleware to catch errors.
import { onError } from "h3";
// Handling errors using middleware
app.use(
onError(event, (event, error) => {
console.error(error);
}),
);
使用嵌套应用时,不会调用子应用的全局钩子函数。因此,最好使用
onError
中间件。¥!TIP
When using nested apps, global hooks of sub-apps will not be called. Therefore it is better to use onError
middleware.