I'm using execSync to run a soffice command. The issue I'm having is when an error is thrown execSync just logs the error to the console there is no way of catching it. I've tried using a try catch statement but it still just logs the error to the console.
function convertToPdf(filepath, destpath) {
var cmd = 'sofice command';
try {
var res = execSync(cmd, { encoding: 'utf8' });
} catch (e) {
console.log("Errors:", e);
}
console.log("res:", res);
}
convertToPdf("test.docx");
I run this and get this back:
Error: source file could not be loaded
res:
Notice how my catch statement is never logged even though an error was clearly thrown but another Error: message is logged automatically because I'm not logging that.
try this:
function myExecSync(command, trim = true, cwd = pwd, opts = {}) {
const ret = execSync(command, { cwd, ...opts }).toString('utf-8');
return trim ? ret.trim() : ret;
}
And write stdio: 'pipe' manually to prevent childprocess.stderr output to the console. like
myExecSync(command, true, cwd, { stdio: 'pipe' })
Related
After going through all related issues regarding stubbing readFile/Sync with Sinon /Chai/ Mocha, the test is failing.
There's a basic getFile function that retrieves a file:
function getFile(path) {
const file = fs.readFileSync(path, "utf8)
return file;
}
module.exports = {getFile}
and I want to create a test where getFile should throw an error if fs.readFileSync also throws an error:
it('should throw an error if fs.readFileSync throws an error', () => {
I tried:
it('should throw an error if fs.readFileSync throws an error', () => {
const error = new Error('some error message')
const myStub = sinon.stub(fs, "readFileSync")
myStub.throws(error)
const filePath = "/Project/test.js"
const gFile = index.getFile(filePath)
try {
if(myStub.error === true) {
gFile(error)
} catch (error) {
expect(myStub).to.throw(error)
What I got was:
1 failing
Error: some error message
at Context.
at process.processImmediate
See the chai expect docs on throw(). There is this example:
var badFn = function () { throw new TypeError('Illegal salmon!'); };
expect(badFn).to.throw();
You see that expect(badFn) gets badFn not badFn(), so nowhere in the test is badFn actually called.
This means that expect calls badFn. And actually, expect needs to be the one to call it because it needs to catch the error.
So in your code, try this:
const stub = sinon.stub(fs, 'readFileSync').throws();
const callGetFile = () => {
index.getFile('some_file');
};
expect(callGetFile).to.throw();
Try putting your error function in the Sinon throw method as below.
myStub.throws(new Error('some error message'));
I am trying to write test cases for the below code:
async readFile(filename) {
try {
const fileStream = fs.createReadStream(filename);
const rs = readline.createInterface({
input: fileStream,
});
} catch (error) {
throw error.message;
}
}
test case:
await expect(readFile('invalid-file.txt')).to.be.rejectedWith(
"ENOENT, no such file or directory 'invalid-file.txt'",
);
I am getting error for the above test case:
Uncaught Error: ENOENT, no such file or directory 'invalid-file.txt'
at Binding.<anonymous> (node_modules/mock-fs/lib/binding.js:383:15)
How to write test case for catch exceptions?
Note: This test is passing in my local, but failing in Travis.
Thanks in advance.
Suppose I have an api.js:
const {somefunction} = require('../controllers/some-controller');
app.get('/data/', somefunction);
some-controller.js:
exports.somefunction = async (req, res,next) => {
const someVariable = req.params.variable
try {
console.log('status',res.statusCode) **//status code is: 200**
const Details = await collectionName.find({}).exec()
res.send(Details)
} catch {
console.log('status',res.statusCode) **//Here also,status code is: 200**
next(ApiError.dbError('Internal Server Error')); //middleware for error handling gives output
//as ApiError { code: 500, message:
//'Internal Server Error' }
return;
}
};
Say I wrote some wrong variable name in res.send(Detaaal) and it goes to catch block
Here even in catch block status code is 200.
I'm trying to understand at what condition is status code different. Why is status code response on fail inside catch block didn't give me 500 status code.
200 is the default code and nothing has happened that would change that.
You haven't written code to change it and, while an exception has been thrown, you caught it, so it never hits Express' own catch logic which would set a 500 error.
The next function, on the other hand, does appear to change it, but you are looking at the value before running that function.
sorry about my poor english
your logic in here cause the problem you are getting everything in collection even its empty
const Details = await collectionName.find({}).exec()
when collection is empty there was no error just return empty array like this[]
You must create a condition to prevent an empty submission from being sent here is my solution
exports.somefunction = async (req, res,next) => {
const someVariable = req.params.variable
try {
console.log('status',res.statusCode) **//status code is: 200**
const Details = await collectionName.find({}).exec()
if (Details.length===0) {
return res.status(404).send();
}
res.send(Details)
} catch {
console.log('status',res.statusCode) **//Here also,status code is: 200**
next(ApiError.dbError('Internal Server Error')); //middleware for error handling gives output
//as ApiError { code: 500, message:
//'Internal Server Error' }
return;
}
};
I'm trying to log errors in an alexa skill that runs in a Lambda function, but no matter what I try, errors somehow get through my try/catch blocks without being logged.
This is my index.js:
const Alexa = require('ask-sdk-core');
try {
const handlers = require('./handlers');
const wrappedHandlers = handlers.map(handler => ({
...handler,
async handle(handlerInput) {
try {
console.log(`Running handler ${handler.name}`, JSON.stringify(handlerInput, null, 2));
const response = await handler.handle(handlerInput);
console.log(`Successfully ran handler ${handler.name}`, JSON.stringify(response, null, 2));
return response;
} catch(error) {
console.log(`Failed to run handler ${handler.name}`, error.stack);
throw error;
}
},
}));
exports.handler = Alexa.SkillBuilders
.custom()
.addRequestHandlers(...wrappedHandlers)
.addErrorHandlers(require('./handlers/error'))
.lambda();
} catch(error) {
console.log('Fatal initialization error', error);
exports.handler = Alexa.SkillBuilders
.custom()
.addRequestHandlers({
canHandle() { return true; },
handle(handlerInput) {
return handlerInput.responseBuilder
.speak(`Initialization error`, error.stack);
},
})
.lambda();
}
The top-level try/catch should catch any errors thrown during require('./handlers'). I've observed this working in the past catching syntax errors in my handlers.
I'm also wrapping every handler's handle function in a try/catch (see wrappedHandlers). My error handler also logs any errors it sees:
// handlers/error.js
module.exports = {
canHandle() { return true; },
handle(handlerInput, error) {
console.log(`Error handled: ${error.stack}`);
// During tests, include the error in the response
if(process.env['NODE_ENV'] === 'test') {
const { attributesManager } = handlerInput;
const sessionAttributes = attributesManager.getSessionAttributes();
sessionAttributes.error = error;
attributesManager.setSessionAttributes(sessionAttributes);
}
const message = error && error.speachMessage || `Sorry, I can't understand the command. Please say again. ${error.stack}`;
return handlerInput.responseBuilder
.speak(message)
.reprompt(message)
.getResponse();
},
};
Despite all of this, the Alexa simulator is spitting out [Error]: An unexpected error occurred., but the cloudwatch logs don't contain any errors or failed requests. How is this possible?
I'm also experiencing this problem and I've got a function which is throwing with a lambda 502 bad gateway, the cloudwatch log entry contains
Invoke Error {"errorType":"UnauthorizedError","errorMessage":"Forbidden","name":"UnauthorizedError","stack":["UnauthorizedError: Forbidden"," at /var/task/ApiServerClass.js:57:27"," at processTicksAndRejections (internal/process/task_queues.js:97:5)"," at async module.exports.me (/var/task/ApiServerClass.js:68:43)"," at async module.exports.run (/var/task/ApplicationClass.js:42:22)"]}
But wrapped around that entire function is a try/catch
It's as if throwing an exception immediately causes lambda to quit and all your exception handling is ignored. But when running local tests through mocha. The exceptions are respected
In the main process of my Electron app, I'm trying to handle an exception thrown when creating a file that already exists. However, my catch clause is never entered, and the exception is spammed to the user. What am I doing wrong?
let file;
try {
// this line throws *uncaught* exception if file exists - why???
file = fs.createWriteStream('/path/to/existing/file', {flags: 'wx'});
}
catch (err) {
// never gets here - why???
}
The correct way to handle this case is by listening to the error event:
const file = fs.createWriteStream('/path/to/existing/file', {flags: 'wx'});
file.on('error', function(err) {
console.log(err);
file.end();
});
What I've found is:
https://github.com/electron/electron/issues/2479
I tried to replicate with pure Node.js, and it catches errors with process.on('uncaughtException', callback)
let desiredPath = '/mnt/c/hello.txt';
let fs = require('fs');
process.on('uncaughtException', function (error) {
console.log('hello1');
});
try {
fs.createWriteStream(desiredPath, {
flags: 'wx',
});
}
catch (err) {
console.log('hello');
}
//Output is: 'hello1'
I tried it with Ubuntu shell on Windows 10, in my case I don't have permissions to read that file and process.on('uncaughtException', callback) catches it correctly.