Skip to content

Commit

Permalink
[Task] #34 improve error handling, log server shutdowns
Browse files Browse the repository at this point in the history
  • Loading branch information
Type-Style committed Feb 7, 2024
1 parent 5c61c66 commit 05a726c
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 14 deletions.
38 changes: 31 additions & 7 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import cache from './cache';
import * as error from "./error";
import writeRouter from '@src/controller/write';
import readRouter from '@src/controller/read';
import path from 'path';
import path from 'path';
import logger from '@src/scripts/logger';

// configurations
Expand All @@ -19,7 +19,7 @@ app.use(
helmet({
contentSecurityPolicy: {
directives: {
"default-src": "'self'",
"default-src": "'self'",
"img-src": "*"
}
}
Expand All @@ -45,7 +45,12 @@ app.use(function (req, res, next) {

// routes
app.get('/', (req, res) => {
res.send('Hello World, via TypeScript and Node.js!');
res.send('Hello World, via TypeScript and Node.js!');
});

app.get('/test', (req, res) => {
res.send('Hello Test!');
process.exit();
});


Expand All @@ -55,20 +60,39 @@ app.use('/read', readRouter);
// use httpdocs as static folder
app.use('/', express.static(path.join(__dirname, 'httpdocs'), {
extensions: ['html', 'txt', "pdf"],
index: "start.html",
index: ["start.html", "start.txt"] ,
}));

// error handling
app.use(error.notFound);
app.use(error.handler);

// init server
app.listen(80, () => {
logger.log(`Server running //localhost:80, ENV: ${process.env.NODE_ENV}`, true);
const server = app.listen(80, () => {
logger.log(`Server running //localhost:80, ENV: ${process.env.NODE_ENV}`, true);
});

// catching shutdowns
['SIGINT', 'SIGTERM', 'exit'].forEach((signal) => {
process.on(signal, () => {
function logAndExit() {
// calling .shutdown allows your process to exit normally
// toobusy.shutdown();
logger.log(`Server shutdown on signal: ${signal} //localhost:80`, true);
process.exit();
}
if (signal != "exit") { // give the server time to shutdown before closing
server.close(logAndExit);
} else {
logger.log(`Server shutdown immediate: ${signal} //localhost:80`, true);
}
});
});

process.on('uncaughtException', function(err) {
// last resort error handling
process.on('uncaughtException', function (err) {
console.error('Caught exception:', err);
logger.error(err);
server.close();
process.exit(1);
});
2 changes: 1 addition & 1 deletion src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export function handler(err: Error, req: Request, res: Response<Response.Error>
stack: process.env.NODE_ENV === "development" ? err.stack : "---"
};

logger.error(responseBody);
logger.error(JSON.stringify(responseBody));
res.json(responseBody);
next();
}
21 changes: 15 additions & 6 deletions src/scripts/logger.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
// primitive text logger
import fs from 'fs'; // typescript will compile to require
import path from 'path'; // typescript will compile to require
import chalk from "chalk"; // keep import syntax after compile
import fs from 'fs';
import path from 'path';
import chalk from "chalk";

const logPath = path.resolve(__dirname, '../httpdocs', 'log.txt');

const dirPath = path.resolve(__dirname, '../httpdocs/log');
const logPath = path.resolve(dirPath, 'start.txt');

if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
console.log("path created")
}

// const logPath = path.resolve(__dirname, '../httpdocs/log', 'start.txt');
const date = new Date().toLocaleString('de-DE', { hour12: false });

export default {
log: (message:string|JSON, showDateInConsole:boolean=false, showLogInTest=false) => {
log: (message: string | JSON, showDateInConsole: boolean = false, showLogInTest = false) => {
message = JSON.stringify(message);
fs.appendFileSync(logPath, `${date} \t|\t ${message} \n`);
if (showDateInConsole) {
Expand All @@ -17,7 +26,7 @@ export default {
console.log(message);
}
},
error: (message:string|JSON|Response.Error) => {
error: (message: string | JSON | Response.Error) => {
fs.appendFileSync(logPath, `${date} \t|\t ERROR: ${message} \n`);
console.error(message);
}
Expand Down

0 comments on commit 05a726c

Please sign in to comment.