chore: add middleware for error handling (#695)

This commit is contained in:
Sainan 2025-01-03 22:25:03 +01:00 committed by GitHub
parent e6432b5052
commit 4756f54f40
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 22 additions and 31 deletions

View File

@ -2,6 +2,7 @@ import express from "express";
import { unknownEndpointHandler } from "@/src/middleware/middleware";
import { requestLogger } from "@/src/middleware/morgenMiddleware";
import { errorHandler } from "@/src/middleware/errorHandler";
import { apiRouter } from "@/src/routes/api";
//import { testRouter } from "@/src/routes/test";
@ -20,7 +21,7 @@ app.use(bodyParser.raw());
app.use(express.json());
app.use(bodyParser.text());
app.use(requestLogger);
//app.use(requestLogger);
app.use(errorHandler);
app.use("/api", apiRouter);
//app.use("/test", testRouter);

View File

@ -30,13 +30,11 @@ export const claimCompletedRecipeController: RequestHandler = async (req, res) =
recipe => recipe._id?.toString() === claimCompletedRecipeRequest.RecipeIds[0].$oid
);
if (!pendingRecipe) {
logger.error(`no pending recipe found with id ${claimCompletedRecipeRequest.RecipeIds[0].$oid}`);
throw new Error(`no pending recipe found with id ${claimCompletedRecipeRequest.RecipeIds[0].$oid}`);
}
//check recipe is indeed ready to be completed
// if (pendingRecipe.CompletionDate > new Date()) {
// logger.error(`recipe ${pendingRecipe._id} is not ready to be completed`);
// throw new Error(`recipe ${pendingRecipe._id} is not ready to be completed`);
// }
@ -45,7 +43,6 @@ export const claimCompletedRecipeController: RequestHandler = async (req, res) =
const recipe = getRecipe(pendingRecipe.ItemType);
if (!recipe) {
logger.error(`no completed item found for recipe ${pendingRecipe._id.toString()}`);
throw new Error(`no completed item found for recipe ${pendingRecipe._id.toString()}`);
}

View File

@ -5,7 +5,6 @@ import { getAccountIdForRequest } from "@/src/services/loginService";
import { getPersonalRooms } from "@/src/services/personalRoomsService";
import { getShip } from "@/src/services/shipService";
import { Loadout } from "@/src/models/inventoryModels/loadoutModel";
import { logger } from "@/src/utils/logger";
import { toOid } from "@/src/helpers/inventoryHelpers";
import { IGetShipResponse } from "@/src/types/shipTypes";
import { IPersonalRooms } from "@/src/types/personalRoomsTypes";
@ -44,8 +43,7 @@ export const getLoadout = async (accountId: string) => {
const loadout = await Loadout.findOne({ loadoutOwnerId: accountId });
if (!loadout) {
logger.error(`loadout not found for account ${accountId}`);
throw new Error("loadout not found");
throw new Error(`loadout not found for account ${accountId}`);
}
return loadout;

View File

@ -17,13 +17,7 @@ import {
import { handleSubsumeCompletion } from "./infestedFoundryController";
export const inventoryController: RequestHandler = async (request, response) => {
let account;
try {
account = await getAccountForRequest(request);
} catch (e) {
response.status(400).send("Log-in expired");
return;
}
const account = await getAccountForRequest(request);
const inventory = await Inventory.findOne({ accountOwnerId: account._id.toString() });

View File

@ -22,7 +22,6 @@ export const startRecipeController: RequestHandler = async (req, res) => {
const recipe = getRecipe(recipeName);
if (!recipe) {
logger.error(`unknown recipe ${recipeName}`);
throw new Error(`unknown recipe ${recipeName}`);
}

View File

@ -0,0 +1,16 @@
import { NextFunction, Request, Response } from "express";
import { logger } from "../utils/logger";
export const errorHandler = (err: Error, req: Request, res: Response, _next: NextFunction): void => {
if (err.message == "Invalid accountId-nonce pair") {
res.status(400).json("Log-in expired");
} else if (err.stack) {
const stackArr = err.stack.split("\n");
stackArr[0] += ` while processing ${req.path} request`;
logger.error(stackArr.join("\n"));
res.status(500).end();
} else {
logger.error(`uncaught error while processing ${req.path} request: ${err.message}`);
res.status(500).end();
}
};

View File

@ -1,5 +1,4 @@
import { getIndexAfter } from "@/src/helpers/stringHelpers";
import { logger } from "@/src/utils/logger";
import {
dict_de,
dict_en,
@ -54,7 +53,6 @@ export const getWeaponType = (weaponName: string): WeaponTypeInternal => {
const weaponType = weaponInfo.productCategory;
if (!weaponType) {
logger.error(`unknown weapon category for item ${weaponName}`);
throw new Error(`unknown weapon category for item ${weaponName}`);
}
@ -83,7 +81,6 @@ export const getItemCategoryByUniqueName = (uniqueName: string): string => {
const index = getIndexAfter(uniqueName, splitWord);
if (index === -1) {
logger.error(`error parsing item category ${uniqueName}`);
throw new Error(`error parsing item category ${uniqueName}`);
}
const category = uniqueName.substring(index).split("/")[0];

View File

@ -1,12 +1,10 @@
import { Loadout } from "@/src/models/inventoryModels/loadoutModel";
import { logger } from "@/src/utils/logger";
export const getLoadout = async (accountId: string) => {
const loadout = await Loadout.findOne({ loadoutOwnerId: accountId });
if (!loadout) {
logger.error(`loadout not found for account ${accountId}`);
throw new Error("loadout not found");
throw new Error(`loadout not found for account ${accountId}`);
}
return loadout;

View File

@ -1,12 +1,10 @@
import { PersonalRooms } from "@/src/models/personalRoomsModel";
import { logger } from "@/src/utils/logger";
export const getPersonalRooms = async (accountId: string) => {
const personalRooms = await PersonalRooms.findOne({ personalRoomsOwnerId: accountId });
if (!personalRooms) {
logger.error(`personal rooms not found for account ${accountId}`);
throw new Error("personal rooms not found");
throw new Error(`personal rooms not found for account ${accountId}`);
}
return personalRooms;
};

View File

@ -47,7 +47,6 @@ export const handleSetShipDecorations = async (
const roomToPlaceIn = rooms.find(room => room.Name === placedDecoration.Room);
if (!roomToPlaceIn) {
logger.error("room not found");
throw new Error("room not found");
}
@ -59,7 +58,6 @@ export const handleSetShipDecorations = async (
);
if (existingDecorationIndex === -1) {
logger.error("decoration to be moved not found");
throw new Error("decoration to be moved not found");
}
@ -143,13 +141,11 @@ export const handleSetPlacedDecoInfo = async (accountId: string, req: ISetPlaced
const room = personalRooms.Ship.Rooms.find(room => room.Name === req.Room);
if (!room) {
logger.error("room not found");
throw new Error("room not found");
}
const placedDeco = room.PlacedDecos?.find(x => x._id.toString() == req.DecoId);
if (!placedDeco) {
logger.error("deco not found");
throw new Error("deco not found");
}

View File

@ -1,6 +1,5 @@
import { Ship } from "@/src/models/shipModel";
import { ILoadoutDatabase } from "@/src/types/saveLoadoutTypes";
import { logger } from "@/src/utils/logger";
import { Types } from "mongoose";
export const createShip = async (
@ -26,7 +25,6 @@ export const getShip = async (shipId: Types.ObjectId, fieldSelection: string = "
const ship = await Ship.findOne({ _id: shipId }, fieldSelection);
if (!ship) {
logger.error(`error finding a ship with id ${shipId.toString()}`);
throw new Error(`error finding a ship with id ${shipId.toString()}`);
}
@ -39,7 +37,6 @@ export const getShipLean = async (shipOwnerId: string) => {
}>("LoadOutInventory.LoadOutPresets");
if (!ship) {
logger.error(`error finding a ship for account ${shipOwnerId}`);
throw new Error(`error finding a ship for account ${shipOwnerId}`);
}