Skip to content

Commit

Permalink
testing error catching
Browse files Browse the repository at this point in the history
  • Loading branch information
dbarkowsky committed Feb 16, 2024
1 parent 83bf3cc commit 37c39d3
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
9 changes: 8 additions & 1 deletion express-api/src/express.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import 'dotenv/config.js';
import express, { Application, RequestHandler } from 'express';
import express, { Application, NextFunction, Request, RequestHandler, Response } from 'express';
import cookieParser from 'cookie-parser';
import compression from 'compression';
import cors from 'cors';
Expand All @@ -12,6 +12,7 @@ import { KEYCLOAK_OPTIONS } from '@/middleware/keycloak/keycloakOptions';
import swaggerUi from 'swagger-ui-express';
import { Roles } from '@/constants/roles';
import swaggerJSON from '@/swagger/swagger-output.json';
import errorHandler from '@/middleware/errorHandler';

const app: Application = express();

Expand Down Expand Up @@ -64,6 +65,11 @@ app.use(`/api/v2`, headerHandler as RequestHandler);
// Unprotected Routes
app.use(`/api/v2/health`, router.healthRouter);

// TODO: Remove after testing
app.use('/error', async (req: Request, res: Response, next: NextFunction) => {
next('test');
});

// Protected Routes
app.use(`/api/v2/ltsa`, protectedRoute(), router.ltsaRouter);
app.use(`/api/v2/admin`, protectedRoute([Roles.ADMIN]), router.adminRouter);
Expand All @@ -78,4 +84,5 @@ app.use(`/api/v2/projects`, protectedRoute(), router.projectsRouter);
app.use(`/api/v2/reports`, protectedRoute(), router.reportsRouter);
app.use(`/api/v2/tools`, protectedRoute(), router.toolsRouter);

app.use(errorHandler);
export default app;
16 changes: 16 additions & 0 deletions express-api/src/middleware/errorHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { ErrorWithCode } from "@/utilities/customErrors/ErrorWithCode";
import { NextFunction, Request, Response } from "express";

const errorHandler = (
err: string | Error | ErrorWithCode,
req: Request,
res: Response,
next: NextFunction,
) => {
const message = err instanceof Error ? err.message : err;
const code = err instanceof ErrorWithCode ? err.code : 400;
res.status(code).send(`it's broken: ${message}`);
next();
};

export default errorHandler;

0 comments on commit 37c39d3

Please sign in to comment.