# Error while executing painless script : Cannot invoke \\"Object.getClass()\\" because \\"receiver\\" is null". Same script is working fine in Dev tools

**URL:** https://discuss.elastic.co/t/error-while-executing-painless-script-cannot-invoke-object-getclass-because-receiver-is-null-same-script-is-working-fine-in-dev-tools/297128
**Category:** Elasticsearch
**Tags:** elastic-stack-alerting, painless
**Created:** [February 14, 2022, 10:55am UTC](https://discuss.elastic.co/t/error-while-executing-painless-script-cannot-invoke-object-getclass-because-receiver-is-null-same-script-is-working-fine-in-dev-tools/297128 "2022-02-14T10:55:47Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![KabirAli07](https://avatars.discourse-cdn.com/v4/letter/k/ee59a6/32.png) [@KabirAli07](https://discuss.elastic.co/u/KabirAli07)
#### Post date: [February 14, 2022, 10:55am UTC](https://discuss.elastic.co/t/error-while-executing-painless-script-cannot-invoke-object-getclass-because-receiver-is-null-same-script-is-working-fine-in-dev-tools/297128/1 "2022-02-14T10:55:48Z")

</div>

```auto
{
  "trigger": {
    "schedule": {
      "interval": "30m"
    }
  },
  "input": {
    "chain": {
      "inputs": [
        {
          "first": {
            "search": {
              "request": {
                "search_type": "query_then_fetch",
                "indices": [
                  "my_logs"
                ],
                "rest_total_hits_as_int": true,
                "body": {
                  "query": {
                    "bool": {
                      "filter": [
                        {
                          "range": {
                            "@timestamp": {
                              "from": "now-1h",
                              "to": "now"
                            }
                          }
                        }
                      ]
                    }
                  },
                  "aggs": {
                    "inst_name": {
                      "terms": {
                        "field": "inst_name.keyword",
                        "size": 10000
                      },
                      "aggs": {
                        "messages": {
                          "filters": {
                            "filters": {
                              "failure": {
                                "match": {
                                  "status": "0"
                                },
                                "siteError": {
                                  "match": {
                                    "error_code.keyword": "SITE"
                                  }
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        {
          "second": {
            "search": {
              "request": {
                "search_type": "query_then_fetch",
                "indices": [
                  "my_logs"
                ],
                "rest_total_hits_as_int": true,
                "body": {
                  "query": {
                    "bool": {
                      "filter": [
                        {
                          "range": {
                            "@timestamp": {
                              "from": "now-30m",
                              "to": "now"
                            }
                          }
                        }
                      ]
                    }
                  },
                  "aggs": {
                    "inst_name": {
                      "terms": {
                        "field": "inst_name.keyword",
                        "size": 10000
                      },
                      "aggs": {
                        "messages": {
                          "filters": {
                            "filters": {
                              "failure": {
                                "match": {
                                  "status": "0"
                                }
                              },
                              "siteError": {
                                "match": {
                                  "error_code.keyword": "SITE"
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      ]
    }
  },
  "condition": {
    "script": {
      "source": """
        def message = "";
        for (first_org_item in ctx.payload.first.aggregations.inst_name.buckets) {
            def first_org_name = first_org_item.key;
            def first_total = first_org_item.doc_count;
            def first_failure_count = first_org_item.messages.buckets.failure.doc_count;
            def first_fail_per = Math.round( first_failure_count * 100 / first_total);
            
            def first_siterr_count = first_org_item.messages.buckets.siteError.doc_count;
            
            def first_site_per = Math.round( first_siterr_count * 100 / first_total);

            for (sec_org_item in ctx.payload.second.aggregations.inst_name.buckets) {
                def sec_org_name = sec_org_item.key;
                def sec_total = sec_org_item.doc_count;
                def sec_failure_count = sec_org_item.messages.buckets.failure.doc_count;
                def sec_fail_per = Math.round( sec_failure_count * 100 / sec_total);
                
                def sec_siterr_count = sec_org_item.messages.buckets.siteError.doc_count;
                def sec_site_per = Math.round( sec_siterr_count * 100 / sec_total);
                
                if (first_org_name == sec_org_name) {
                    if (sec_fail_per > first_fail_per ) {
                        def diff = sec_fail_per - first_fail_per;
                        message += "Error [Alert]:" + first_org_name +" Institution Overall failure percentage increased by " + diff +"% in last 30mins" +(String)(char)0x0a;
                    }
                    if (sec_site_per > first_site_per) {
                        def s_diff = sec_site_per - first_site_per;
                        message += "Error [Alert]:" + first_org_name +" Institution Site failure percentage increased by " + s_diff +"% in last 30mins" +(String)(char)0x0a;
                    }
                    
                }
            }
           
        }
        if(message.equals("")){
             return false;   
        }
        else{
            ctx.payload["result"] = message;
            return true;
        }
       """,
      "lang": "painless"
    }
  },
  "actions": {
    "slack_webhook": {
      "webhook": {
        "scheme": "https",
        "host": "hooks.slack.com",
        "port": 443,
        "method": "post",
        "path": "/services/T1LHPRL20/B02NASMCLU8/bKM7Pd54WctoZf2uRi4oCWlN",
        "params": {
          "watch_id": "{{ctx.watch_id}}"
        },
        "headers": {
          "Content-Type": "application/json"
        },
        "body": """ __json__ ::{"text": "{{ctx.payload.result}}"}"""
      }
    }
  }
}

```

Error is

```auto

    "actions": []
  },
  "exception": {
    "type": "script_exception",
    "reason": "runtime error",
    "script_stack": [
      "for (first_org_item in ctx.payload.first.aggregations.inst_name.buckets) {\n def ",
      " ^---- HERE"
    ],
    "script": " ...",
    "lang": "painless",
    "position": {
      "offset": 88,
      "start": 35,
      "end": 126
    },
    "caused_by": {
      "type": "null_pointer_exception",
      "reason": null,
      "stack_trace": "java.lang.NullPointerException\n\tat org.elasticsearch.painless.DefBootstrap$PIC.fallback(DefBootstrap.java:209)\n\tat org.elasticsearch.painless.PainlessScript$Script.execute( ...:89)\n\tat org.elasticsearch.xpack.watcher.condition.ScriptCondition.doExecute(ScriptCondition.java:60)\n\tat org.elasticsearch.xpack.watcher.condition.ScriptCondition.execute(ScriptCondition.java:55)\n\tat org.elasticsearch.xpack.watcher.execution.ExecutionService.executeInner(ExecutionService.java:512)\n\tat org.elasticsearch.xpack.watcher.execution.ExecutionService.execute(ExecutionService.java:319)\n\tat org.elasticsearch.xpack.watcher.transport.actions.execute.TransportExecuteWatchAction$1.doRun(TransportExecuteWatchAction.java:158)\n\tat org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37)\n\tat org.elasticsearch.xpack.watcher.execution.ExecutionService$WatchExecutionTask.run(ExecutionService.java:626)\n\tat org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:684)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)\n\tat java.lang.Thread.run(Thread.java:748)\n"
    },
    "stack_trace": "ScriptException[runtime error]; nested: NullPointerException;\n\tat org.elasticsearch.painless.PainlessScript.convertToScriptException(PainlessScript.java:96)\n\tat org.elasticsearch.painless.PainlessScript$Script.execute( ...:1)\n\tat org.elasticsearch.xpack.watcher.condition.ScriptCondition.doExecute(ScriptCondition.java:60)\n\tat org.elasticsearch.xpack.watcher.condition.ScriptCondition.execute(ScriptCondition.java:55)\n\tat org.elasticsearch.xpack.watcher.execution.ExecutionService.executeInner(ExecutionService.java:512)\n\tat org.elasticsearch.xpack.watcher.execution.ExecutionService.execute(ExecutionService.java:319)\n\tat org.elasticsearch.xpack.watcher.transport.actions.execute.TransportExecuteWatchAction$1.doRun(TransportExecuteWatchAction.java:158)\n\tat org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37)\n\tat org.elasticsearch.xpack.watcher.execution.ExecutionService$WatchExecutionTask.run(ExecutionService.java:626)\n\tat org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:684)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)\n\tat java.lang.Thread.run(Thread.java:748)\nCaused by: java.lang.NullPointerException\n\tat org.elasticsearch.painless.DefBootstrap$PIC.fallback(DefBootstrap.java:209)\n\tat org.elasticsearch.painless.PainlessScript$Script.execute( ...:89)\n\t... 11 more\n"
  }

```

 ![Screenshot from 2022-02-14 16-31-27](https://us1.discourse-cdn.com/elastic/original/3X/0/a/0a0561c3001bc21113c6d2beef2765fb2efdfc83.png)

---

<div class="post-metadata">

### Author: ![jakelandis](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jakelandis/32/36163_2.png) [@jakelandis](https://discuss.elastic.co/u/jakelandis)
#### Post date: [February 14, 2022, 9:03pm UTC](https://discuss.elastic.co/t/error-while-executing-painless-script-cannot-invoke-object-getclass-because-receiver-is-null-same-script-is-working-fine-in-dev-tools/297128/2 "2022-02-14T21:03:14Z")

</div>

Not a direct answer to question, but the error means that `ctx.payload.first.aggregations` is null. A logging action + \_execute can help to troubleshoot:

For example:

```auto
"actions": {
        "my_logger": {
            "logging": {
                "text": "Watch payload = {{ctx.payload.first}}",
                "level": "debug"
            }
        }
    }

```

Then use the [\_execute API](https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-execute-watch.html#watcher-api-execute-watch-example) to execute the Watch . To use the execute API, you can generally just to wrap the whole watch in a `"watch" : { <your watch here> }` ) and review the output of the `ctx.payload` .

The Painless [null safe operator](https://www.elastic.co/guide/en/elasticsearch/painless/current/painless-operators-reference.html#null-safe-operator) `?.` can often help with Null Pointers.

I would also suggest to use `{{ctx.trigger.scheduled_time}}` instead of `now` for time in case Watcher gets backed up for some reason.

---

<div class="post-metadata">

### Author: ![KabirAli07](https://avatars.discourse-cdn.com/v4/letter/k/ee59a6/32.png) [@KabirAli07](https://discuss.elastic.co/u/KabirAli07)
#### Post date: [February 15, 2022, 6:29am UTC](https://discuss.elastic.co/t/error-while-executing-painless-script-cannot-invoke-object-getclass-because-receiver-is-null-same-script-is-working-fine-in-dev-tools/297128/3 "2022-02-15T06:29:35Z")

</div>

> [@jakelandis](#):
>
> Then use the [\_execute API](https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-execute-watch.html#watcher-api-execute-watch-example) to execute the Watch . To use the execute API, you can generally just to wrap the whole watch in a `"watch" : { <your watch here> }` ) and review the output of the `ctx.payload` .

Hi jakelandis,  
I have tried this `Then use the _execute API to execute the Watch . To use the execute API, you can generally just to wrap the whole watch in a "watch" : { <your watch here> } ) and review the output of the ctx.payload .`

in dev tools i'm getting expected output without any error but same in watcher i got this null\_pointer \_exception.

As i mention if i remove this piece of code it works fine in watcher

```auto
"siteError": {
                                  "match": {
                                    "error_code.keyword": "SITE"
                                  }
                                }

```

can you please suggests on this.

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)
#### Post date: [March 15, 2022, 6:30am UTC](https://discuss.elastic.co/t/error-while-executing-painless-script-cannot-invoke-object-getclass-because-receiver-is-null-same-script-is-working-fine-in-dev-tools/297128/4 "2022-03-15T06:30:33Z")

</div>

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