{"record":{"id":"0fbbbc94e0081471","repo":"karatelabs/karate","slug":"methodname-called-on-null-or-undefined","errorCode":null,"errorMessage":"${methodName} called on null or undefined","messagePattern":"(.+?) called on null or undefined","errorType":"exception","errorClass":"JsErrorException (typeError)","httpStatus":null,"severity":"error","filePath":"karate-js/src/main/java/io/karatelabs/js/Terms.java","lineNumber":1506,"sourceCode":"        int eIdx = s.indexOf('E');\n        if (eIdx < 0) return s;\n        String mantissa = s.substring(0, eIdx);\n        String exp = s.substring(eIdx + 1);\n        if (mantissa.endsWith(\".0\")) mantissa = mantissa.substring(0, mantissa.length() - 2);\n        if (exp.charAt(0) != '+' && exp.charAt(0) != '-') exp = \"+\" + exp;\n        return mantissa + \"e\" + exp;\n    }\n\n    /**\n     * Spec {@code RequireObjectCoercible} (§7.2.1) — gate at the top of every\n     * built-in whose receiver feeds {@code ToObject} / {@code ToString} (e.g.\n     * {@code String.prototype.*}). null / undefined throw TypeError; everything\n     * else passes through. {@code methodName} is woven into the message so the\n     * thrown error reads like a JS engine's, not a generic NPE.\n     */\n    public static void requireObjectCoercible(Object value, String methodName) {\n        if (value == null || value == UNDEFINED) {\n            throw JsErrorException.typeError(methodName + \" called on null or undefined\");\n        }\n    }\n\n    public static String toStringCoerce(Object o, CoreContext context) {\n        if (o instanceof String s) {\n            return s;\n        }\n        // §7.1.17 ToString throws for a symbol. String(sym) is the one operation\n        // that does not (JsString.getObject special-cases it), and ToPropertyKey\n        // has its own branch above, so both stay reachable.\n        if (o instanceof JsSymbol) {\n            throw JsErrorException.typeError(\"Cannot convert a Symbol value to a string\");\n        }\n        if (o instanceof Number n) {\n            return numberToString(n);\n        }\n        if (o == null) {\n            return \"null\";","sourceCodeStart":1488,"sourceCodeEnd":1524,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-js/src/main/java/io/karatelabs/js/Terms.java#L1488-L1524","documentation":"Methods like String.prototype helpers require the `this` value to be object-coercible. Terms.requireObjectCoercible throws a TypeError naming the method when it is invoked on null or undefined, producing a message that reads like a JS engine's instead of a generic NPE.","triggerScenarios":"Calling e.g. `null.toString()`, `undefined.trim()`, or a String.prototype method with `this` = null/undefined inside karate-js expressions or script functions.","commonSituations":"Chained calls on values that can be null/undefined, e.g. `(response.headers['x'] || '').trim()` written without the fallback, or map lookups returning undefined then having a method called on them.","solutions":["Add a null/undefined fallback before the method call: (v ?? '').trim()","Short-circuit: if (v != null) v.trim();","Use optional chaining where supported: v?.trim()"],"exampleFix":"// before\nvar t = response.token.trim();\n// after\nvar t = (response.token ?? '').trim();","handlingStrategy":"type-guard","validationCode":"if (v === null || v === undefined) throw new Error('value required before calling ' + methodName);","typeGuard":"function isObjectCoercible(v) { return v !== null && v !== undefined; }","tryCatchPattern":"try { t = v.trim(); } catch (e) { if (String(e).includes('called on null or undefined')) t = ''; else throw e; }","preventionTips":["Apply (v ?? '') fallbacks at ingestion of nullable data","Use optional chaining (v?.method()) in scripts","Validate response fields before method chains"],"tags":["javascript","null","type-error"],"backgroundTag":"null-argument","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-16T19:17:19.609Z"}