Add better error handling and logging

master
Dessa Simpson 2020-07-02 13:06:13 -07:00
parent b7d8f14eb4
commit 75e5022090
3 changed files with 17 additions and 6 deletions

View File

@ -3,6 +3,7 @@ import * as requests from "./requests";
import { QueryResult } from "pg";
import express from "express";
import db from "./db";
import errorHandler from "./errors";
const app = express();
app.use(express.static('public'));
@ -11,13 +12,13 @@ app.use(express.urlencoded({extended: false}));
app.get("/api/getRequests", async (request, response) => {
var requestCount = ( request.query.count ? parseInt(request.query.count as string, 10) : 5 );
requests.getRequests(requestCount).then((val: QueryResult) => response.send(val))
.catch((e: any) => console.error(e.stack));
.catch((e: any) => errorHandler(request,response,e));
});
app.get("/api/getAllRequests", async (request, response) => {
var requestCount = ( request.query.count ? parseInt(request.query.count as string, 10) : 5 );
requests.getAllRequests(requestCount).then((val: QueryResult) => response.send(val))
.catch((e: any) => console.error(e.stack));
.catch((e: any) => errorHandler(request,response,e));
});
app.post("/api/addRequest", async (request, response) => {
@ -35,7 +36,7 @@ app.post("/api/addRequest", async (request, response) => {
var url = request.body.url as string;
var requester = request.body.requester as string;
requests.addRequest(url,requester).then((val: string) => response.send(val))
.catch((e: any) => console.error(e.stack));
.catch((e: any) => errorHandler(request,response,e));
});
app.post("/api/updateRequestScore", async (request, response) => {
@ -53,7 +54,7 @@ app.post("/api/updateRequestScore", async (request, response) => {
var url = request.body.url as string;
var scoreDiff = parseInt(request.body.scoreDiff as string, 10);
requests.updateRequestScore(url,scoreDiff).then((val: string) => response.send(val))
.catch((e: any) => console.error(e.stack));
.catch((e: any) => errorHandler(request,response,e));
});
app.post("/api/deleteRequest", async (request, response) => {
@ -65,7 +66,7 @@ app.post("/api/deleteRequest", async (request, response) => {
}
var url = request.body.url as string;
requests.deleteRequest(url).then((val: string) => response.send(val))
.catch((e: any) => console.error(e.stack));
.catch((e: any) => errorHandler(request,response,e));
});
const server = app.listen(config.port, () => {

11
src/errors.ts Normal file
View File

@ -0,0 +1,11 @@
import express from "express";
function errorHandler(request: express.Request, response: express.Response, e: any) {
response.status(500);
response.send("Internal server error");
console.log("Exception hit!");
console.log(`Request path: ${request.route.path}`);
console.log(e.stack);
}
export = errorHandler;

View File

@ -1,4 +1,3 @@
import express from "express";
import pg from "pg";
import db from "./db";