Search code examples
javascriptnode.jstry-catchreferenceerror

Used Reference in javascript is not available inside the catch-Block


Inside our Javascript-Code we have a try...catch-block. The class works like the following:

const ourCustomClassFile = require('./customFile');

Inside customFile.js we defined a function

const sendErrorNotification = (source, reason, scriptposition) => 
{ ...something and write a mail... 
}

our main-program got a try-catch block over the whole script like this:

const ourCustomClassFile = require('./customFile');
try{
   const inputFolder = this.config.folder.input;    
   const workFolder = this.config.folder.work;  
   const errorFolder = this.config.folder.error;
}catch(error){
   if (fs.existsSync(workFile)) {
               fs.renameSync(workFile, errorFile);
        }

   sendErrorNotification(
        file,
        `Errortext: ${error}`,
        actPosition
           );   
}

The function sendErrorNotification works fine inside the normal code of our main program, but inside the catch-block we get an Exception:

UnhandledPromiseRejectionWarning: ReferenceError: sendErrorNotification is not defined

So I just Need to know: why is the function not defined?


Solution

  • inside your customFile.js

    const sendErrorNotification = (source, reason, scriptposition) => { 
      ...something and write a mail... 
    }
    module.exports = {
      sendErrorNotification: sendErrorNotification
    }
    
    

    then, in your main.js file, call it like this:

    const ourCustomClassFile = require('./customFile');
    ...
    ourCustomClassFile.sendErrorNotification(..)
    ...