scaryguy
scaryguy

Reputation: 7950

Callbacks and error handling in an asynchronous function

I'm trying to improve my understanding of callbacks/error handling/async structure of Node.js working on challenges at nodeschool.io.

I have one local module file and one actual program file. Here they are:

my_module.js

module.exports = function(path, extension, callback) {
    var fs = require('fs');
    if (path) {
        fs.readdir(path, function(err, list) {
            if (err) return callback(err);
            var filtered = list.filter(function(item) {
                //console.log(item.split("."));
                if (item.split(".")[1] == extension) return item
            })
            callback(null, filtered);
        })
    } else {
        callback("===> Please provide a directory path.")
    }
}

program.js

var my_module = require('./my_module');
var path = process.argv[2];
var extension = process.argv[3];

my_module(path, extension, function(err, data) {
    if (err) return new Error(err);
    console.log(data.join("\n"));
})

This program works just fine. BUT when it should give an error, it doesn't.

Inside my_module.js, if path variable is empty I want to give the error "Please provide a directory path.". The weird thing is, when I write console.log instread of callback, I can show the message. But when I call the callback as callback("===> Please provide a directory path.") nothing happens. No errors, it's silent.

Why is this? And how to fix that?

Thanks

Upvotes: 1

Views: 1946

Answers (2)

Timothy Johns
Timothy Johns

Reputation: 1095

You may want to throw that error rather than return it, depending on the error handling pattern for your application.

var my_module = require('./my_module');
var path = process.argv[2];
var extension = process.argv[3];

my_module(path, extension, function(err, data) {
    if (err) throw new Error(err);
    console.log(data.join("\n"));
})

As a recommendation, since process.arg[] contains user-specified input, I'd actually recommend doing the parameter checking with user-friendly (pretty) error messages (rather than an exception) BEFORE calling my_module(). my_module() itself can then be modified to check and throw an exception if any bogus parameters are passed in.

Upvotes: 0

Chirag Jain
Chirag Jain

Reputation: 2418

It is silent because in your program.js, you are not consuming the error.

Think program.js is going to consume your module. module.js doesn't know what to do with error. it just passes the err and data to your program.js which consumes it. So its the responsibility of program.js to do whatever it wants to with the error. Something like log it on console, etc.

Try this:

my_module(path, extension, function(err, data) {
    if (err) return console.log(err);
    console.log(data.join("\n"));
})

Upvotes: 5

Related Questions