{"record":{"id":"210a58681f9ab873","repo":"karatelabs/karate","slug":"cannot-convert-null-or-undefined-to-object","errorCode":null,"errorMessage":"Cannot convert null or undefined to object","messagePattern":"Cannot convert null or undefined to object","errorType":"exception","errorClass":"JsErrorException","httpStatus":null,"severity":"error","filePath":"karate-js/src/main/java/io/karatelabs/js/JsDatePrototype.java","lineNumber":213,"sourceCode":"\n    private Object toUTCString(Context context, Object[] args) {\n        JsDate d = requireDate(context);\n        if (d.isInvalid()) {\n            return \"Invalid Date\";\n        }\n        return formatUtc(d);\n    }\n\n    /**\n     * Spec Date.prototype.toJSON: works on ANY object (not just Date) per\n     * §21.4.4.37. ToPrimitive(this, hint Number); if Number+non-finite return null;\n     * else Invoke(O, \"toISOString\"). The unusual generic-this pattern is why\n     * this method does NOT use {@link #requireDate}.\n     */\n    private Object toJSON(Context context, Object[] args) {\n        Object o = context.getThisObject();\n        if (o == null || o == Terms.UNDEFINED) {\n            throw JsErrorException.typeError(\"Cannot convert null or undefined to object\");\n        }\n        CoreContext cc = cc(context);\n        Object tv = o;\n        if (o instanceof ObjectLike && cc != null) {\n            tv = Terms.toPrimitive(o, \"number\", cc);\n            if (cc.isError()) return null;\n        } else if (o instanceof JsValue jv) {\n            tv = jv.getJsValue();\n        }\n        if (tv instanceof Number n && !Double.isFinite(n.doubleValue())) {\n            return null;\n        }\n        // Direct shortcut for Date this — produce ISO string. Avoids the generic\n        // Invoke(O, \"toISOString\") path doing a redundant getMember dispatch.\n        if (o instanceof JsDate d) {\n            return formatIso(d);\n        }\n        // Invoke O.toISOString()","sourceCodeStart":195,"sourceCodeEnd":231,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-js/src/main/java/io/karatelabs/js/JsDatePrototype.java#L195-L231","documentation":"Date.prototype.toJSON uses the generic-this pattern (it can delegate to any object with a toISOString), but null and undefined have no object wrapper, so it throws this TypeError per spec §20.4.4.37 step 1. Other primitives are accepted and coerced via ToPrimitive.","triggerScenarios":"Date.prototype.toJSON.call(null), .call(undefined), or JSON.stringify(null/undefined-derived values reaching the Date.toJSON path; also `null.toJSON()` style access routed through this prototype method.","commonSituations":"JSON.stringify of records where a Date field is sometimes null/undefined, API responses with missing dates, template code that assumes a field is always a Date.","solutions":["Guard for null/undefined before serializing: only call toJSON / stringify when the value is a Date.","Use a replacer function in JSON.stringify that maps null dates to a safe value.","Fix the data source so the field is always a Date object or explicitly omitted."],"exampleFix":"// before\nconst s = JSON.stringify({ d: maybeDate }); // TypeError if maybeDate is null via toJSON path\n// after\nconst s = JSON.stringify({ d: maybeDate instanceof Date ? maybeDate : null });","handlingStrategy":"type-guard","validationCode":"if (value == null) return null; // skip serialization of absent dates","typeGuard":"function isDateLike(v) { return v !== null && v !== undefined && typeof v === 'object'; }","tryCatchPattern":"try { return JSON.stringify(payload); } catch (e) { if (e instanceof TypeError && /null or undefined/.test(e.message)) return JSON.stringify(withNullDates(payload)); throw e; }","preventionTips":["Normalize date fields to Date or null before serialization.","Use a JSON.stringify replacer to handle null/undefined dates.","Treat missing API date fields explicitly instead of letting them flow into toJSON."],"tags":["javascript","date","json","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"}