( error: Error, req: ExpressRequestWithContext, res: Response, _next: NextFunction, )
| 33 | }; |
| 34 | |
| 35 | async function errorHandlingMiddleware( |
| 36 | error: Error, |
| 37 | req: ExpressRequestWithContext, |
| 38 | res: Response, |
| 39 | _next: NextFunction, |
| 40 | ): Promise<void> { |
| 41 | try { |
| 42 | const monkeyError = error as MonkeyError; |
| 43 | let status = 500; |
| 44 | const data: { errorId?: string; uid: string } = { |
| 45 | errorId: monkeyError.errorId ?? uuidv4(), |
| 46 | uid: monkeyError.uid ?? req.ctx?.decodedToken?.uid, |
| 47 | }; |
| 48 | let message = "Unknown error"; |
| 49 | |
| 50 | if (/ECONNREFUSED.*27017/i.test(error.message)) { |
| 51 | message = "Could not connect to the database. It may be down."; |
| 52 | } else if (error instanceof URIError || error instanceof SyntaxError) { |
| 53 | status = 400; |
| 54 | message = "Unprocessable request"; |
| 55 | } else if (error instanceof MonkeyError) { |
| 56 | message = error.message; |
| 57 | status = error.status; |
| 58 | } else { |
| 59 | message = `Oops! Our monkeys dropped their bananas. Please try again later. - ${data.errorId}`; |
| 60 | } |
| 61 | |
| 62 | await incrementBadAuth(req, res, status); |
| 63 | |
| 64 | if (status >= 400 && status < 500) { |
| 65 | recordClientErrorByVersion(req.headers["x-client-version"] as string); |
| 66 | } |
| 67 | |
| 68 | if (!isDevEnvironment() && status >= 500 && status !== 503) { |
| 69 | recordServerErrorByVersion(version); |
| 70 | |
| 71 | const { uid, errorId } = data as { |
| 72 | uid: string; |
| 73 | errorId: string; |
| 74 | }; |
| 75 | |
| 76 | try { |
| 77 | await addLog( |
| 78 | "system_error", |
| 79 | `${status} ${errorId} ${error.message} ${error.stack}`, |
| 80 | uid, |
| 81 | ); |
| 82 | await db.collection<DBError>("errors").insertOne({ |
| 83 | _id: errorId, |
| 84 | timestamp: Date.now(), |
| 85 | status: status, |
| 86 | uid, |
| 87 | message: error.message, |
| 88 | stack: error.stack, |
| 89 | endpoint: req.originalUrl, |
| 90 | method: req.method, |
| 91 | url: req.url, |
| 92 | }); |
nothing calls this directly
no test coverage detected