add route logging and a generic error handler for routes
This commit is contained in:
parent
35d78dc617
commit
415b9f8928
48
src/route/messages.ts
Normal file
48
src/route/messages.ts
Normal file
@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Creates the base message for web responses
|
||||
*
|
||||
* @param message the message to send
|
||||
* @returns the message
|
||||
*/
|
||||
function baseMessage(error: boolean, message: string) {
|
||||
return {
|
||||
error,
|
||||
message,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an error message for web responses
|
||||
*
|
||||
* @param message the message to send
|
||||
* @returns the message
|
||||
*/
|
||||
function errorMessage(message: string) {
|
||||
return baseMessage(true, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a success message for web responses
|
||||
*
|
||||
* @param message the message to send
|
||||
* @returns the message
|
||||
*/
|
||||
function successMessage(message: string) {
|
||||
return baseMessage(false, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a message for an internal server error
|
||||
*
|
||||
* @returns the message
|
||||
*/
|
||||
function internalServerError() {
|
||||
return errorMessage("Internal Server Error");
|
||||
}
|
||||
|
||||
export const ServerMessages = {
|
||||
baseMessage,
|
||||
errorMessage,
|
||||
successMessage,
|
||||
internalServerError,
|
||||
};
|
@ -1,4 +1,5 @@
|
||||
import express, { Express } from "express";
|
||||
import { ServerMessages } from "../route/messages";
|
||||
import { Route } from "../route/route";
|
||||
|
||||
type ServerConfig = {
|
||||
@ -32,13 +33,26 @@ export default class Server {
|
||||
this.server = express();
|
||||
this.preInit();
|
||||
|
||||
// Setup route logging
|
||||
this.server.use((req, res, next) => {
|
||||
// TODO: make this look better?
|
||||
console.log(`[${req.method}] ${req.path}`);
|
||||
next();
|
||||
});
|
||||
|
||||
// Handle the routes
|
||||
for (const route of this.routes) {
|
||||
this.server.all(route.getPath(), (req, res, next) => {
|
||||
if (req.method.toUpperCase() !== route.getMethod().toUpperCase()) {
|
||||
return next(); // Skip this method
|
||||
}
|
||||
route.handle(req, res, next);
|
||||
try {
|
||||
route.handle(req, res, next);
|
||||
} catch (ex) {
|
||||
console.error(ex);
|
||||
// Inform the user that an internal server error occurred
|
||||
res.status(500).json(ServerMessages.internalServerError());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user