Browse Source

fix大小写

refactor
dash 3 months ago
parent
commit
62ec22a335
  1. BIN
      database/development.sqlite3-shm
  2. 43
      src/middlewares/ErrorHandler/index.js

BIN
database/development.sqlite3-shm

Binary file not shown.

43
src/middlewares/ErrorHandler/index.js

@ -0,0 +1,43 @@
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)
}
}
}
Loading…
Cancel
Save