แก้ throw error

This commit is contained in:
DESKTOP-2S5P7D1\Windows 10 2024-12-18 18:59:51 +07:00
parent 8c483a95a1
commit 537a388bcb
2 changed files with 47 additions and 40 deletions

View file

@ -164,12 +164,12 @@ class CheckAuth {
port: process.env.REDIS_PORT, port: process.env.REDIS_PORT,
}) })
const getAsync = promisify(redisClient.get).bind(redisClient) const getAsync = promisify(redisClient.get).bind(redisClient)
let reply = await getAsync("org_" + keycloakId) try {
if (reply != null) { let reply = await getAsync("org_" + keycloakId)
reply = JSON.parse(reply) if (reply != null) {
} else { reply = JSON.parse(reply)
try { } else {
if (!keycloakId) throw "Error calling API No KeycloakId" if (!keycloakId) throw new Error("No KeycloakId provided")
const x = await new CallAPI().GetData( const x = await new CallAPI().GetData(
{ {
headers: { authorization: token }, headers: { authorization: token },
@ -187,10 +187,10 @@ class CheckAuth {
} }
return data return data
} catch (error) {
console.error("Error calling API:", error)
throw error
} }
} catch (error) {
console.error("Error calling API:", error)
throw error
} }
} }
public async PermissionCreate(req: RequestWithUser, system: string) { public async PermissionCreate(req: RequestWithUser, system: string) {

View file

@ -19,12 +19,10 @@ const LOG_LEVEL_MAP: Record<string, number> = {
const elasticsearch = new Client({ const elasticsearch = new Client({
node: `${process.env.ELASTICSEARCH_PROTOCOL}://${process.env.ELASTICSEARCH_HOST}:${process.env.ELASTICSEARCH_PORT}`, node: `${process.env.ELASTICSEARCH_PROTOCOL}://${process.env.ELASTICSEARCH_HOST}:${process.env.ELASTICSEARCH_PORT}`,
}) })
async function logMiddleware(req: Request, res: Response, next: NextFunction) { async function logMiddleware(req: Request, res: Response, next: NextFunction) {
if (!req.url.startsWith("/api/")) return next() if (!req.url.startsWith("/api/")) return next()
let data: any let data: any
const originalJson = res.json const originalJson = res.json
res.json = function (v: any) { res.json = function (v: any) {
@ -38,41 +36,50 @@ async function logMiddleware(req: Request, res: Response, next: NextFunction) {
req.app.locals.logData = {} req.app.locals.logData = {}
res.on("finish", async () => { res.on("finish", async () => {
if (!req.url.startsWith("/api/")) return try {
if (!req.url.startsWith("/api/")) return
const level = LOG_LEVEL_MAP[process.env.LOG_LEVEL ?? "debug"] || 4 const level = LOG_LEVEL_MAP[process.env.LOG_LEVEL ?? "debug"] || 4
if (level === 1 && res.statusCode < 500) return if (level === 1 && res.statusCode < 500) return
if (level === 2 && res.statusCode < 400) return if (level === 2 && res.statusCode < 400) return
if (level === 3 && res.statusCode < 200) return if (level === 3 && res.statusCode < 200) return
let token: any const token = req.headers["authorization"]
token = req.headers["authorization"] let rootId = null
const rootId = await new permission().checkOrg(token, req.app.locals.logData.userId) try {
rootId = token ? await new permission().checkOrg(token, req.app.locals.logData.userId) : null
} catch (err) {
console.warn("Error fetching rootId:", err)
}
const obj = { const obj = {
logType: res.statusCode >= 500 ? "error" : res.statusCode >= 400 ? "warning" : "info", logType: res.statusCode >= 500 ? "error" : res.statusCode >= 400 ? "warning" : "info",
ip: req.ip, ip: req.ip,
rootId: rootId ? rootId.orgRootId : null, rootId: rootId?.orgRootId ?? null,
systemName: "probation", systemName: "evaluation",
startTimeStamp: timestamp, startTimeStamp: timestamp,
endTimeStamp: new Date().toISOString(), endTimeStamp: new Date().toISOString(),
processTime: performance.now() - start, processTime: performance.now() - start,
host: req.hostname, host: req.hostname,
method: req.method, method: req.method,
endpoint: req.url, endpoint: req.url,
responseCode: String(res.statusCode === 304 ? 200 : res.statusCode), responseCode: String(res.statusCode === 304 ? 200 : res.statusCode),
responseDescription: data?.message, responseDescription: data?.message,
input: (level === 4 && JSON.stringify(req.body, null, 2)) || undefined, input: level === 4 ? JSON.stringify(req.body, null, 2) : undefined,
output: (level === 4 && JSON.stringify(data, null, 2)) || undefined, output: level === 4 ? JSON.stringify(data, null, 2) : undefined,
...req.app.locals.logData, ...req.app.locals.logData,
}
// Send log to Elasticsearch
await elasticsearch.index({
index: ELASTICSEARCH_INDEX,
document: obj,
})
} catch (err) {
console.error("Error in logMiddleware:", err)
} }
elasticsearch.index({
index: ELASTICSEARCH_INDEX,
document: obj,
})
}) })
return next() return next()