I need to create a .log file, which each time I run my code, saves me information, shows me if it ran successfully or if it had an error. I made a code so that each time the code runs correctly it does so and it works fine, the problem I'm having now is that, if I have an error and it doesn't run, it shows me the success message in the same way, when it should show the Error message.
Here's my code:
// inserts data to a DB
function insertOffice(index) {
...
}
// Loops the function in order to make an insert each 0.5 seconds
function myLoop() {
setTimeout(function () {
let response = insertOffice(i);
console.log('Running...');
i++;
if (i < offices.length) {
myLoop();
}
}, 500)
}
// Runs the looper.
try {
myLoop();
logger.info('Success');
} catch (error) {
console.log(error);
logger.error(new Error(error));
}
here's my Winston config:
import * as winston from 'winston';
import { format, createLogger, transports } from "winston";
const { timestamp, combine, printf } = format;
const logFormat = printf(({ message, timestamp, stack }) => {
return `${timestamp} : ${stack || message}`;
});
export const logger = createLogger({
format: combine(
format.colorize(),
timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
format.errors({ stack: true }),
logFormat
),
'transports': [
new winston.transports.File({
filename: 'logs/example.log'
})
]
});
As you can see, the plan is to run the function inside a try catch, so when it fails (goes to the catch) it shows me the logger.error(new Error(error));
but it seems it is not entering the catch.
When I do an insert and everything works fine, in my example.log
file, it should be written:
2022-02-03 08:25:18 : Success
And it does, but when I write an error in my code on purpose, to check if it works also for the message error, it doesn't, it still writes the succes message.
I already searched some questions here, like this one for example, but it doesn't seems to me, to fit in my error.
It should be written in my example.log
the timestamp and the message error, but it doesn't.
Is it the right way to write the message error?
EDIT: I searched and watched this question that may because maybe, the settimeout was causing the error, but I'm still getting the same result, the Success message is written and not the error one.
I noticed it can be an issue with the try catch, but I can't find a solution to that.
EDIT: I added what Mojtaba told me to, looking this way:
function myLoop() {
setTimeout(function () {
try {
let response = insertOffice(i);
i++;
if (i < offices.length) {
myLoop();
}
//throw Error('unexpected Error');
console.log('success');
} catch (error) {
console.log('failed');
}
}, 500)
}