You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
17 lines
700 B
17 lines
700 B
import { send, setResponseStatus } from "h3";
|
|
|
|
/**
|
|
* 将 API 路由上 `createError({ data: { error } })` 的 body 以 JSON 返回(与规格一致)。
|
|
*/
|
|
export default defineNitroPlugin((nitroApp) => {
|
|
nitroApp.hooks.hook("error", async (error, ctx) => {
|
|
const event = ctx.event;
|
|
if (!event?.path?.startsWith("/api/")) return;
|
|
const err = error as { statusCode?: number; data?: unknown };
|
|
const data = err.data as { error?: { code: string; message: string } } | undefined;
|
|
if (!data?.error) return;
|
|
if (event.node.res.headersSent) return;
|
|
setResponseStatus(event, err.statusCode ?? 500);
|
|
await send(event, JSON.stringify(data), "application/json");
|
|
});
|
|
});
|
|
|