# Handling Errors of Function External Module

**URL:** https://discourse.nodered.org/t/handling-errors-of-function-external-module/62029
**Category:** General
**Tags:** function-node
**Created:** [1 May 2022 13:13 UTC](https://discourse.nodered.org/t/handling-errors-of-function-external-module/62029 "2022-05-01T13:13:40Z")
**Posts on this page:** 10
**Page:** 1

<div class="post-metadata">

### Author: ![Nasro](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/nasro/32/43232_2.png) [@Nasro](https://discourse.nodered.org/u/Nasro)
#### Post date: [1 May 2022 13:13 UTC](https://discourse.nodered.org/t/handling-errors-of-function-external-module/62029/1 "2022-05-01T13:13:40Z")

</div>

Hi  
i am using [node-zklib](https://github.com/caobo171/node-zklib) package  
it works but if there any error NR will stop running because of Uncaught Exception  
my question is how can i **handle all errors** of this module to prevent NR form Stop ?

This is a sample of error

```auto
1 May 13:46:02 - [red] Uncaught Exception:
1 May 13:46:02 - UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "#<ZKError>".

C:\Users\USER>

```

---

<div class="post-metadata">

### Author: ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)
#### Post date: [1 May 2022 13:25 UTC](https://discourse.nodered.org/t/handling-errors-of-function-external-module/62029/2 "2022-05-01T13:25:01Z")

</div>

I assume you are using this module in a function node?

Show us your code & we can advise.

---

<div class="post-metadata">

### Author: ![Nasro](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/nasro/32/43232_2.png) [@Nasro](https://discourse.nodered.org/u/Nasro)
#### Post date: [1 May 2022 13:33 UTC](https://discourse.nodered.org/t/handling-errors-of-function-external-module/62029/3 "2022-05-01T13:33:16Z")

</div>

Yes i am using function node

 ![zklib](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/7/b/7b84da8beeb211cf9b5fda1c29725d72f6442ddd.png)

```auto
//172.16.12.201
const test = async () => {

    let zkInstance = new ZKLib('172.16.12.201', 4370, 10000, 4000);
    try {
        // Create socket to machine 
        await zkInstance.createSocket()

        // Get general info like logCapacity, user counts, logs count
        // It's really useful to check the status of device 
        node.warn(await zkInstance.getInfo())
    } catch (e) {
        node.warn(e)
        if (e.code === 'EADDRINUSE') {
        }
    }

    // Get users in machine 
    const users = await zkInstance.getUsers()
    node.warn(users)

    // Get all logs in the machine 
    // Currently, there is no filter to take data, it just takes all !!
    const logs = await zkInstance.getAttendances()
    node.warn(logs)

    const attendances = await zkInstance.getAttendances((percent, total) => {
        // this callbacks take params is the percent of data downloaded and total data need to download 
    })

    // YOu can also read realtime log by getRealTimelogs function

    // node.warn('check users', users)

    zkInstance.getRealTimeLogs((data) => {
        // do something when some checkin 
        node.warn(data)
    })

    // delete the data in machine
    // You should do this when there are too many data in the machine, this issue can slow down machine 
    

    // Get the device time
    //const getTime = await zkInstance.getTime();
    //node.warn(getTime.toString());

    // Disconnect the machine ( don't do this when you need realtime update :))) 
    await zkInstance.disconnect()

}

test()

return msg;

```

Please note that the main topic is how to handle the error to prevent stopping NR not how solve the error

---

<div class="post-metadata">

### Author: ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)
#### Post date: [1 May 2022 13:37 UTC](https://discourse.nodered.org/t/handling-errors-of-function-external-module/62029/4 "2022-05-01T13:37:58Z")

</div>

Everywhere you have an await you should be surrounded by `try` `catch` (or wrap the whole inner of the function in a `try` `catch`

```auto
  try {
    await zkInstance.disconnect()
  } catch(e) {
    node.error(e, msg);
    return;
  }

```

---

<div class="post-metadata">

### Author: ![Nasro](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/nasro/32/43232_2.png) [@Nasro](https://discourse.nodered.org/u/Nasro)
#### Post date: [1 May 2022 13:45 UTC](https://discourse.nodered.org/t/handling-errors-of-function-external-module/62029/5 "2022-05-01T13:45:26Z")

</div>

I try it but same result error can't be handled

```auto
1 May 14:42:22 - [red] Uncaught Exception:
1 May 14:42:22 - UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "#<ZKError>".

C:\Users\USER>

```

---

<div class="post-metadata">

### Author: ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)
#### Post date: [1 May 2022 14:05 UTC](https://discourse.nodered.org/t/handling-errors-of-function-external-module/62029/6 "2022-05-01T14:05:24Z")

</div>

> [@Nasro](#):
>
> I try it but same result error can't be handled

Please post your code as it is now

---

<div class="post-metadata">

### Author: ![Nasro](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/nasro/32/43232_2.png) [@Nasro](https://discourse.nodered.org/u/Nasro)
#### Post date: [1 May 2022 15:25 UTC](https://discourse.nodered.org/t/handling-errors-of-function-external-module/62029/7 "2022-05-01T15:25:41Z")

</div>

Sorry i didn't do exactly what you said  
Now the error is handled  
But the content of error can't be displayed

```auto
{"message":"[object Object]","source":{"id":"0b8889d8e8629a19","type":"function","name":"zklib","count":1}}

```

Here is my code

```auto
//172.16.12.201
const test = async () => {

    let zkInstance = new ZKLib('172.16.12.201', 4370, 10000, 4000);
    try {
        // Create socket to machine 
        await zkInstance.createSocket()

        // Get general info like logCapacity, user counts, logs count
        // It's really useful to check the status of device 
        node.warn(await zkInstance.getInfo())
    } catch (e) {
        node.error(e, msg);
        node.warn(e)
        if (e.code === 'EADDRINUSE') {
        }
    }

    // Get users in machine 

    
    try {
    const users = await zkInstance.getUsers()
    node.warn(users)

  } catch(e) {
    node.error(e, msg);
    return;
  }

    

    // Get all logs in the machine 
    // Currently, there is no filter to take data, it just takes all !!
    
    const logs = await zkInstance.getAttendances()
    node.warn(logs)

    try {
       const attendances = await zkInstance.getAttendances((percent, total) => {
        // this callbacks take params is the percent of data downloaded and total data need to download 
    })
  } catch(e) {
    node.error(e, msg);
    return;
  }

    // YOu can also read realtime log by getRealTimelogs function

    // node.warn('check users', users)
/*
    zkInstance.getRealTimeLogs((data) => {
        // do something when some checkin 
        node.warn(data)
    })

*/

    // delete the data in machine
    // You should do this when there are too many data in the machine, this issue can slow down machine 
    

    // Get the device time
    //const getTime = await zkInstance.getTime();
    //node.warn(getTime.toString());

    // Disconnect the machine ( don't do this when you need realtime update :))) 
   

    try {
    await zkInstance.disconnect()
  } catch(e) {
    node.error(e, msg);
    return;
  }

}

test()

return msg;

```

---

<div class="post-metadata">

### Author: ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)
#### Post date: [1 May 2022 15:28 UTC](https://discourse.nodered.org/t/handling-errors-of-function-external-module/62029/8 "2022-05-01T15:28:39Z")

</div>

> [@Nasro](#):
>
> But the content of error can't be displayed

Is that from the warn or the error?

Put `console.error(e);` below `node.error(e, msg);`, & check the console - what do you see?  
Change `node.warn(e)` to `node.warn({error: e});`, what do you see?

---

<div class="post-metadata">

### Author: ![Nasro](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/nasro/32/43232_2.png) [@Nasro](https://discourse.nodered.org/u/Nasro)
#### Post date: [8 May 2022 10:47 UTC](https://discourse.nodered.org/t/handling-errors-of-function-external-module/62029/9 "2022-05-08T10:47:04Z")

</div>

Hi  
after period of success of handling error  
now i have some unhandled error

```auto
8 May 11:32:56 - [red] Uncaught Exception:
8 May 11:32:56 - TypeError: Cannot read property 'removeListener' of null
    at internalCallback (C:\Users\USER\.node-red\node_modules\node-zklib\zklibtcp.js:116:21)
    at Timeout._onTimeout (C:\Users\USER\.node-red\node_modules\node-zklib\zklibtcp.js:129:13)
    at listOnTimeout (node:internal/timers:555:17)
    at processTimers (node:internal/timers:498:7)

```

This is my code even i catch all the possible error

```auto
//172.16.12.201
const test = async () => {

  let zkInstance = new ZKLib('172.16.12.201', 4370, 10000);
  try {
    // Create socket to machine 
    await zkInstance.createSocket()

    // Get general info like logCapacity, user counts, logs count
    // It's really useful to check the status of device 
    node.warn(await zkInstance.getInfo())
  } catch (e) {

    node.warn(["Create socket", { "error": e }])
    node.error(e, msg);
    console.error(e)

    if (e.code === 'EADDRINUSE') {
    }
  }

  // Get users in machine 

  try {
    var users = await zkInstance.getUsers()
    node.warn(users)

  } catch (e) {
    node.warn(["getUsers", { "error": e }])
    node.error(e, msg);
    console.error(e)
    return;
  }

  // Get all logs in the machine 
  // Currently, there is no filter to take data, it just takes all !!

  try {
    var logs = await zkInstance.getAttendances()
    

    for (let log_list = 0; log_list < logs.data.length; log_list++) {
      let newDate=new Date(logs.data[log_list].recordTime).toLocaleString("en-GB")
      logs.data[log_list].recordTime = newDate.slice(0, 10) + newDate.slice(11);//remove comma 
      for (let usr_list = 0; usr_list < users.data.length; usr_list++) {
        if (users.data[usr_list].userId == logs.data[log_list].deviceUserId) {
          
          logs.data[log_list].name = users.data[usr_list].name
        }
      }

    }
    node.warn(logs)
    
    
    

  } catch (e) {
    node.warn(["getAttendances", { "error": e }])
    node.error(e, msg);
    console.error(e)
    return;
  }

  try {
    const getTime = await zkInstance.getTime()
    node.warn(getTime.toLocaleString("en-GB")
    );
    
  } catch (e) {
    node.warn(["getTime", { "error": e }])
    node.error(e, msg);
    console.error(e)
    return;
  }

   

  try {
    node.warn(["Read saved data", await zkInstance.executeCmd(11)])

  } catch (e) {
    node.warn(["Read saved data", { "error": e }])
    node.error(e, msg);
    console.error(e)
    return;
  }

   try {
    await zkInstance.freeData()
    
    
    
  } catch (e) {
     node.warn(["freeData()", { "error": e }])
    node.error(e, msg);
    console.error(e)
    return;
  }

  try {
    await zkInstance.disconnect()
  } catch (e) {
    node.warn(["disconnect", { "error": e }])
    node.error(e, msg);
    console.error(e)
    return;
  }

  return logs;

}

msg=test()

return msg;

```

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)
#### Post date: [7 July 2022 10:47 UTC](https://discourse.nodered.org/t/handling-errors-of-function-external-module/62029/10 "2022-07-07T10:47:30Z")

</div>

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.
