# Nodered keeps restarting with processTicksAndRejections error

**URL:** <https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956>\
**Category:** General\
**Created:** [26 March 2023 10:02 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956 "2023-03-26T10:02:36Z")\
**Posts on this page:** 16\
**Page:** 2

<div class="post-metadata">

**Author:** ![klose54](https://avatars.discourse-cdn.com/v4/letter/k/ecd19e/32.png) [@klose54](https://discourse.nodered.org/u/klose54)\
**Post date:** [7 April 2023 06:59 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/22 "2023-04-07T06:59:27Z")

</div>

Yes that's what I've edited the last time, but like I said it returned me the error

`[node-red-contrib-surepet/surepet] TypeError: Cannot convert undefined or null to object (line:55)`

So I tried to add something to handle an undefined or null object in the async function like this

```auto

    async function SurePetCredentials(n){
        RED.nodes.createNode(this, n);
        this.username = n.username || this.credentials.username;
        this.password = n.password || this.credentials.password;
        this.client = new SurePet.SurePetCareClient();
        if (this.username && this.password){
            this.log("We have a username and password, attempting to authenticiate.")
            try{
                await this.client.authenticate(this.username, this.password);            
                this.status({fill:"green",shape:"dot",text:"Connected."});
                } catch (err){
                this.status({fill:"red",shape:"ring",text:err});
                }
           

 if (typeof this.client.authenticate() !== 'undefined' && this.client.authenticate() !== null) {
                }
            else {
            this.log('⛔️ Object null ');}
        }

    }

```

Then i get

`[error] Error: Authentication failed: received 422 Unprocessable Entity`

During the Nodered restart

---

<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:** [7 April 2023 07:43 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/23 "2023-04-07T07:43:06Z")

</div>

> [@klose54](#):
>
> Then i get
> 
> `[error] Error: Authentication failed: received 422 Unprocessable Entity`

Sorry, I was trying to guide you to an answer  
I will be more specific. This code will never work....

> [@klose54](#):
>
> ```auto
> if (typeof this.client.authenticate() !== 'undefined' && this.client.authenticate() !== null) {
> }
> else {
> this.log('⛔️ Object null ');}
> }
> 
> ```

Delete it and try again.

Also, could you please try the promise version I wrote here....

> [@Steve-Mcl](#):
>
> try changing this function...
> 
> ```auto
> function SurePetCredentials(n){
> RED.nodes.createNode(this, n);
> this.username = n.username || this.credentials.username;
> this.password = n.password || this.credentials.password;
> this.client = new SurePet.SurePetCareClient();
> const node = this
> if (this.username && this.password){
> this.log("We have a username and password, attempting to authenticate.")
>             
> this.client.authenticate(this.username, this.password)
> .then(() => node.status({fill:"green",shape:"dot",text:"Connected.")
> .catch(err => node.status({fill:"red",shape:"ring",text:err}))
> }
> }
> 
> ```

Exactly as written.

---

<div class="post-metadata">

**Author:** ![klose54](https://avatars.discourse-cdn.com/v4/letter/k/ecd19e/32.png) [@klose54](https://discourse.nodered.org/u/klose54)\
**Post date:** [7 April 2023 13:35 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/24 "2023-04-07T13:35:07Z")

</div>

So after testing the code I modify the node status for .then() to be accurate, like this :

```auto
    function SurePetCredentials(n){
        RED.nodes.createNode(this, n);
        this.username = n.username || this.credentials.username;
        this.password = n.password || this.credentials.password;
        this.client = new SurePet.SurePetCareClient();
        const node = this
        if (this.username && this.password){
            this.log("We have a username and password, attempting to authenticate.")
            
            this.client.authenticate(this.username, this.password)
           .then(() => node.status({fill:"green",shape:"dot",text:"Connected."}))
           .catch(err => node.status({fill:"red",shape:"ring",text:err}))
        }
    }

```

Nodered is deployed well, flows are started, I get informations from the API as usual. Now I have to make it run for a while and see if I still get crash from timeout errors.

Again @Steve-Mcl a big thank you for your help and your time on this subject, it means a lot to me.

---

<div class="post-metadata">

**Author:** ![klose54](https://avatars.discourse-cdn.com/v4/letter/k/ecd19e/32.png) [@klose54](https://discourse.nodered.org/u/klose54)\
**Post date:** [9 April 2023 10:25 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/25 "2023-04-09T10:25:47Z")

</div>

Hi, so after two days of running, unfortunately I still get the exact same crashes from time to time

```auto
[red] Uncaught Exception:
[error] Error: Get state failed: received 504 Gateway Time-out
    at SurePetCareClient.getState (/home/klose54/.node-red/node_modules/sure-pet-care-client/dist/client.js:41:31)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

```

---

<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:** [9 April 2023 10:44 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/26 "2023-04-09T10:44:18Z")

</div>

> [@klose54](#):
>
> `at SurePetCareClient.getState`

So if you look in the file `surepet.js` you should find a call to `.getState()` and it probably doesnt have a catch block or is not handling the timeout correctly.

Can you paste exactly the full content of your `surepet.js` as it is right now.

---

<div class="post-metadata">

**Author:** ![klose54](https://avatars.discourse-cdn.com/v4/letter/k/ecd19e/32.png) [@klose54](https://discourse.nodered.org/u/klose54)\
**Post date:** [9 April 2023 11:21 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/27 "2023-04-09T11:21:16Z")

</div>

```auto
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SurePetCareClient = void 0;
const node_fetch_1 = __importDefault(require("node-fetch"));
class SurePetCareClient {
    constructor() {
        this.token = '';
        this.baseUrl = 'https://app.api.surehub.io';
        this.authenticate = async (email, password) => {
            const resp = await node_fetch_1.default(`${this.baseUrl}/api/auth/login`, {
                method: 'POST',
                body: JSON.stringify({ email_address: email, password, device_id: '.' }),
                headers: { 'Content-Type': 'application/json' },
            });
            if (!resp.ok) {
                switch (resp.status) {
                    case 401:
                        throw new Error('Authentication failed: invalid credentials');
                    default:
                        throw new Error(`Authentication failed: received ${resp.status} ${resp.statusText}`);
                }
            }
            const token = resp.headers.get('Authorization');
            if (token === null) {
                throw new Error('Authentication failed: no authorization token in response');
            }
            this.token = token;
        };
        this.getState = async () => {
            const resp = await node_fetch_1.default(`${this.baseUrl}/api/me/start`, {
                headers: { 'Content-Type': 'application/json', 'Authorization': this.token },
            });
            if (!resp.ok) {
                switch (resp.status) {
                    case 401:
                        throw new Error('Get state failed: unauthenticated');
                    default:
                        throw new Error(`Get state failed: received ${resp.status} ${resp.statusText}`);
                }
            }
            const { data } = await resp.json();
            return data;
        };
        this.getPets = async () => {
            const state = await this.getState();
            return state.pets;
        };
        this.getPetByName = async (name) => {
            const pets = await this.getPets();
            const pet = pets.find((p) => p.name.toLowerCase() === name.toLowerCase());
            if (!pet) {
                throw new Error('Pet not found');
            }
            return pet;
        };
        this.getPetById = async (id) => {
            const pets = await this.getPets();
            const pet = pets.find((p) => p.id === id);
            if (!pet) {
                throw new Error('Pet not found');
            }
            return pet;
        };
        this.setPetLocation = async (id, location, since = new Date()) => {
            const date = since.toISOString();
            const resp = await node_fetch_1.default(`${this.baseUrl}/api/pet/${id}/position`, {
                method: 'POST',
                body: JSON.stringify({ since: date, where: location }),
                headers: { 'Content-Type': 'application/json', 'Authorization': this.token },
            });
            if (!resp.ok) {
                switch (resp.status) {
                    case 401:
                        throw new Error('Set pet location failed failed: invalid credentials');
                    default:
                        throw new Error(`Set pet location failed failed: received ${resp.status} ${resp.statusText}`);
                }
            }
        };
    }
}
exports.SurePetCareClient = SurePetCareClient;

```

---

<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:** [9 April 2023 11:44 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/28 "2023-04-09T11:44:32Z")

</div>

that is not the right file. I want to see where `getState` is called by the contrib node.

It will be file `node_modules/node-red-contrib-surepet/surepet.js`

---

<div class="post-metadata">

**Author:** ![klose54](https://avatars.discourse-cdn.com/v4/letter/k/ecd19e/32.png) [@klose54](https://discourse.nodered.org/u/klose54)\
**Post date:** [9 April 2023 12:04 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/29 "2023-04-09T12:04:57Z")

</div>

The one in `node_modules/node-red-contrib-surepet/surepet.js` is the exact same one as `/.node-red/node_modules/node-red-contrib-surepet/surepet.js`

---

<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:** [9 April 2023 12:20 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/30 "2023-04-09T12:20:11Z")

</div>

Then something is very wrong.

It should look like a node-red module. i.e. the first line will read `module.exports = function(RED){` (what you pasted is a class file)

It should look like this: [node-red-contrib-surepet/surepet.js at 548e3d50560bb9af4b4a38195c72e43495da02d0 · jpwsutton/node-red-contrib-surepet · GitHub](https://github.com/jpwsutton/node-red-contrib-surepet/blob/548e3d50560bb9af4b4a38195c72e43495da02d0/surepet.js#L1)

---

<div class="post-metadata">

**Author:** ![klose54](https://avatars.discourse-cdn.com/v4/letter/k/ecd19e/32.png) [@klose54](https://discourse.nodered.org/u/klose54)\
**Post date:** [9 April 2023 18:42 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/31 "2023-04-09T18:42:34Z")

</div>

So just to be clear, the file at `node_modules/node-red-contrib-surepet/surepet.js` is the exact same one as `/.node-red/node_modules/node-red-contrib-surepet/surepet.js`

Here is the following :

```auto
module.exports = function(RED){
    "use strict"
    var SurePet = require('sure-pet-care-client');

    function SurePetNode(config){
        RED.nodes.createNode(this, config);
        this.surepet = RED.nodes.getNode(config.surepet);
        var node = this;
        //console.log(config);
        node.on('input', function(msg){

            if(config.mode === 'list_pets'){
            this.surepet.client.getPets().then((pets) =>{
                msg.payload = {
                    pets: pets
                }
                node.send(msg)
            })
        } else if(config.mode === "get_status"){
            this.surepet.client.getState().then((state) => {
                msg.payload = state;
                node.send(msg);
            })

        }

            /*
            msg.payload = {
                surepet: this.surepet,
                pets:
            }
            node.send(msg);*/
        });
    }
    RED.nodes.registerType("surepet", SurePetNode);

    function SurePetCredentials(n){
        RED.nodes.createNode(this, n);
        this.username = n.username || this.credentials.username;
        this.password = n.password || this.credentials.password;
        this.client = new SurePet.SurePetCareClient();
        const node = this
        if (this.username && this.password){
             this.log("We have a username and password, attempting to authenticiate.")
            this.client.authenticate(this.username, this.password)
           .then(() => node.status({fill:"green",shape:"dot",text:"Connecté."}))
           .catch(err => node.status({fill:"red",shape:"ring",text:err}))
        }
    }

    RED.nodes.registerType("surepet-credentials",SurePetCredentials,{
        credentials: {
            username: {type:"text"},
            password: {type:"password"}
        }
    });
}

```

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [9 April 2023 20:19 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/32 "2023-04-09T20:19:34Z")

</div>

> [@klose54](#):
>
> the file at `node_modules/node-red-contrib-surepet/surepet.js` is the exact same one as `/.node-red/node_modules/node-red-contrib-surepet/surepet.js`

There should not be one at ~/node\_modules/node-red-contrib-surepet/surepet.js. If there is that probably means that you manually installed the node from your home folder instead of from ~/.node-red. You can safely ignore the one in ~/node\_modules. The one in .node-red/node\_modules is the one you need to adjust.

---

<div class="post-metadata">

**Author:** ![klose54](https://avatars.discourse-cdn.com/v4/letter/k/ecd19e/32.png) [@klose54](https://discourse.nodered.org/u/klose54)\
**Post date:** [10 April 2023 10:52 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/33 "2023-04-10T10:52:27Z")

</div>

Thanks for the explanation, I was wondering why I only get this one at two differents folders, I will delete the useless one.

So for now the file at `/.node-red/node_modules/node-red-contrib-surepet/surepet.js` is the one I paste on my previous post.

---

<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:** [10 April 2023 13:10 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/34 "2023-04-10T13:10:53Z")

</div>

@klose54

Try replacing that files content with the code below

Changes:

1. Ensure all promise calls have a `.catch` block & that `node.error()` is called upon error (so a use can catch errors with the catch node
2. Add "connect" msg support. This way, you can send a msg with a topic of "connect" to change (or reconnect) at runtime (pass the `username` and `password` in the `msg` or `msg.payload`

```auto
module.exports = function (RED) {
    "use strict"
    const SurePet = require('sure-pet-care-client');

    function SurePetNode(config) {
        RED.nodes.createNode(this, config);
        const node = this;
        node.surepet = RED.nodes.getNode(config.surepet);

        node.on('input', function (msg) {

            // special case, if `topic` === connect, then re-authenticate
            if (msg.topic === "connect") {
                node.surepet.client = new SurePet.SurePetCareClient();
                node.surepet.client.authenticate(msg.username || msg.payload?.username, msg.password || msg.payload?.password)
                .then(() => node.status({ fill: "green", shape: "dot", text: "Connected." }))
                .catch(err => {
                    node.error(err, msg)
                    node.status({ fill: "red", shape: "ring", text: err })
                })
                return
            }

            // normal operation
            if (config.mode === 'list_pets') {
                node.surepet.client.getPets().then((pets) => {
                    msg.payload = {
                        pets: pets
                    }
                    node.send(msg)
                }).catch((err) => {
                    node.error(err, msg);
                })
            } else if (config.mode === "get_status") {
                node.surepet.client.getState().then((state) => {
                    msg.payload = state;
                    node.send(msg);
                }).catch((err) => {
                    node.error(err, msg);
                })
            } 
        });
    }
    RED.nodes.registerType("surepet", SurePetNode);

    function SurePetCredentials(n) {
        RED.nodes.createNode(this, n);
        const node = this
        node.username = n.username || node.credentials.username;
        node.password = n.password || node.credentials.password;
        node.client = new SurePet.SurePetCareClient();
        if (node.username && node.password) {
            node.log("We have a username and password, attempting to authenticate.")
            node.client.authenticate(node.username, node.password)
                .then(() => node.status({ fill: "green", shape: "dot", text: "Connected." }))
                .catch(err => {
                    node.status({ fill: "red", shape: "ring", text: err })
                    node.error(err)
                })
        }
    }

    RED.nodes.registerType("surepet-credentials", SurePetCredentials, {
        credentials: {
            username: { type: "text" },
            password: { type: "password" }
        }
    });
}

```

---

<div class="post-metadata">

**Author:** ![klose54](https://avatars.discourse-cdn.com/v4/letter/k/ecd19e/32.png) [@klose54](https://discourse.nodered.org/u/klose54)\
**Post date:** [10 April 2023 13:30 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/35 "2023-04-10T13:30:51Z")

</div>

@Steve-Mcl Your edits deployed well, API is answering. Let's see how things goes for some time. Thank you.

---

<div class="post-metadata">

**Author:** ![klose54](https://avatars.discourse-cdn.com/v4/letter/k/ecd19e/32.png) [@klose54](https://discourse.nodered.org/u/klose54)\
**Post date:** [10 April 2023 17:28 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/36 "2023-04-10T17:28:24Z")

</div>

@Steve-Mcl

I think the problem is now solved thank to your last edit. This afternoon I did not have a single reboot of nodered but I get some error msg in when there was server time out.

![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/0/4/04b139ec2d93b7563f1e3b89c09f744380e19e70.png)

Again, thanks a lot for your help. 🙂

I will update the github with your code for other users after some more days of observation but things are getting really well.

---

<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:** [24 April 2023 17:29 UTC](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956/37 "2023-04-24T17:29:24Z")

</div>

Closed on 24 April 2023 17:29 UTC

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

[Previous page](https://discourse.nodered.org/t/nodered-keeps-restarting-with-processticksandrejections-error/76956.md?page=1)
