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.
43 lines
1.5 KiB
43 lines
1.5 KiB
import { logger } from "@/logger"
|
|
// src/plugins/errorHandler.js
|
|
// 错误处理中间件插件
|
|
|
|
async function formatError(ctx, status, message, stack) {
|
|
const accept = ctx.accepts("json", "html", "text")
|
|
const isDev = process.env.NODE_ENV === "development"
|
|
if (accept === "json") {
|
|
ctx.type = "application/json"
|
|
ctx.body = isDev && stack ? { success: false, error: message, stack } : { success: false, error: message }
|
|
} else if (accept === "html") {
|
|
ctx.type = "html"
|
|
await ctx.render("error/index", { status, message, stack, isDev })
|
|
} else {
|
|
ctx.type = "text"
|
|
ctx.body = isDev && stack ? `${status} - ${message}\n${stack}` : `${status} - ${message}`
|
|
}
|
|
ctx.status = status
|
|
}
|
|
|
|
export default function errorHandler() {
|
|
return async (ctx, next) => {
|
|
// 拦截 Chrome DevTools 探测请求,直接返回 204
|
|
if (ctx.path === "/.well-known/appspecific/com.chrome.devtools.json") {
|
|
ctx.status = 204
|
|
ctx.body = ""
|
|
return
|
|
}
|
|
try {
|
|
await next()
|
|
if (ctx.status === 404) {
|
|
await formatError(ctx, 404, "Resource not found")
|
|
}
|
|
} catch (err) {
|
|
logger.error(err)
|
|
const isDev = process.env.NODE_ENV === "development"
|
|
if (isDev && err.stack) {
|
|
console.error(err.stack)
|
|
}
|
|
await formatError(ctx, err.statusCode || 500, err.message || err || "Internal server error", isDev ? err.stack : undefined)
|
|
}
|
|
}
|
|
}
|
|
|