{"record":{"id":"69a081b17d10de67","repo":"FasterXML/jackson-databind","slug":"deserializationproblemhandler-handlenullforprimit","errorCode":null,"errorMessage":"`DeserializationProblemHandler.handleNullForPrimitives()` for type %s returned value of type %s","messagePattern":"`DeserializationProblemHandler\\.handleNullForPrimitives\\(\\)` for type (.+?) returned value of type (.+?)","errorType":"exception","errorClass":"InvalidFormatException","httpStatus":null,"severity":"error","filePath":"src/main/java/tools/jackson/databind/DeserializationContext.java","lineNumber":1575,"sourceCode":"     */\n    public Object handleNullForPrimitives(Class<?> targetClass,\n            JsonParser p, ValueDeserializer<?> deser,\n            String msgTemplate, Object... msgArgs)\n        throws JacksonException\n    {\n        // but if not handled, just throw exception\n        LinkedNode<DeserializationProblemHandler> h = _config.getProblemHandlers();\n        String msg = _format(msgTemplate, msgArgs);\n        while (h != null) {\n            // Can bail out if it's handled\n            Object instance = h.value().handleNullForPrimitives(this, targetClass, p, deser, msg);\n            if (instance != DeserializationProblemHandler.NOT_HANDLED) {\n                // Sanity check for broken handlers, otherwise nasty to debug:\n                if (_isCompatible(targetClass, instance)) {\n                    return instance;\n                }\n                // In case our problem handler providing incompatible value,\n                throw new InvalidFormatException(_parser,\n                        \"`DeserializationProblemHandler.handleNullForPrimitives()` for type %s returned value of type %s\".formatted(\n                                ClassUtil.nameOf(targetClass), ClassUtil.getClassDescription(instance)),\n                    instance, targetClass\n                        );\n            }\n            h = h.next();\n        }\n        return reportInputMismatch(deser, msg);\n    }\n    /**\n     * Method that deserializers should call if they fail to instantiate value\n     * due to lack of viable instantiator (usually creator, that is, constructor\n     * or static factory method). Method should be called at point where value\n     * has not been decoded, so that handler has a chance to handle decoding\n     * using alternate mechanism, and handle underlying content (possibly by\n     * just skipping it) to keep input state valid\n     *\n     * @param instClass Type that was to be instantiated","sourceCodeStart":1557,"sourceCodeEnd":1593,"githubUrl":"https://github.com/FasterXML/jackson-databind/blob/87876ca5c0569b4933aec2d30d6225e4b9ba3a43/src/main/java/tools/jackson/databind/DeserializationContext.java#L1557-L1593","documentation":"Thrown by DeserializationContext.handleNullForPrimitives() when a registered DeserializationProblemHandler returns a non-null value for a null-to-primitive coercion but that value's type is incompatible with the target primitive type. Jackson validates the handler's return value via _isCompatible() to catch buggy handlers early, since silent type mismatches on primitives would cause confusing downstream errors.","triggerScenarios":"Registering a custom DeserializationProblemHandler that overrides handleNullForPrimitives() and returns a value that is not assignable to the target primitive's wrapper type. For example, the handler returns a String \"0\" when the target is int, or returns a Long when the target is a double field (though wrapper compatibility is checked for primitives).","commonSituations":"Custom problem handlers designed to supply defaults for null primitives that return the wrong Java type. Handlers returning null explicitly (which is allowed). Handlers returning domain objects instead of primitive-compatible values.","solutions":["Ensure your handleNullForPrimitives() returns a value whose type matches or is a wrapper of the targetClass parameter (e.g., return Integer 0 for int targetClass).","Return DeserializationProblemHandler.NOT_HANDLED if your handler cannot handle the specific case, letting other handlers or the default behavior take over.","Add a type check in your handler: if (!targetClass.isInstance(myDefault)) return NOT_HANDLED; before returning."],"exampleFix":"// before\n@Override\npublic Object handleNullForPrimitives(DeserializationContext ctxt, Class<?> targetType,\n        JsonParser p, ValueDeserializer<?> deser, String msg) {\n    return \"0\"; // wrong: String is not compatible with int\n}\n// after\n@Override\npublic Object handleNullForPrimitives(DeserializationContext ctxt, Class<?> targetType,\n        JsonParser p, ValueDeserializer<?> deser, String msg) {\n    if (targetType == int.class) return 0;\n    return NOT_HANDLED;\n}","handlingStrategy":"validation","validationCode":"// Validate handler return type before returning\n@Override\npublic Object handleNullForPrimitives(DeserializationContext ctxt, Class<?> targetType,\n        JsonParser p, ValueDeserializer<?> deser, String msg) {\n    Object candidate = computeDefault(targetType);\n    if (candidate != null && !targetType.isInstance(candidate)\n        && !(targetType.isPrimitive() && ClassUtil.wrapperType(targetType).isInstance(candidate))) {\n        return DeserializationProblemHandler.NOT_HANDLED; // let default handle it\n    }\n    return candidate;\n}","typeGuard":"boolean isHandlerValueCompatible(Class<?> target, Object value) {\n    if (value == null || target.isInstance(value)) return true;\n    return target.isPrimitive() && ClassUtil.wrapperType(target).isInstance(value);\n}","tryCatchPattern":null,"preventionTips":["Return NOT_HANDLED from your handler when unsure of type compatibility.","Match the handler return type exactly to the targetClass wrapper.","Unit-test the handler for each primitive type it may encounter."],"tags":["problem-handler","deserialization","null-handling","primitives","custom-handler"],"backgroundTag":null,"analyzedSha":"87876ca5c0569b4933aec2d30d6225e4b9ba3a43","analyzedAt":"2026-08-11T12:55:24.033Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}