40 examples
Missing null check
Failure to verify null values, causing runtime exceptions.
[ FAQ1 ]
What is a missing null check?
A missing null check occurs when code attempts to use or access properties of an object or value without first verifying if it's null or undefined. This typically results in runtime errors such as null pointer exceptions or type errors, causing the application to crash or behave unpredictably. Missing null checks are common pitfalls in programming, especially when handling optional or dynamically retrieved data, where the presence of valid values isn't guaranteed.
[ FAQ2 ]
How to fix missing null checks
To fix missing null checks, always explicitly verify values for null or undefined before accessing their properties or methods. Employ safe coding practices like conditional checks (
if (value !== null)
), optional chaining (value?.property
), or null-coalescing operators to handle potentially null or undefined values gracefully. Regularly test code paths with both valid and null inputs to proactively identify and address missing null checks. Utilizing static analysis tools or linters can help automatically detect and flag code missing essential null or undefined checks, significantly improving application stability.
diff block
greptile
logic: Missing null check on five_year_age_brackets. Object.entries() will throw if undefined
suggested fix
+ const populationPyramidData = Object.entries(dataInRadius?.population_data?.five_year_age_brackets || {}).map(([ageGroup, count]) => ({
ageGroup: ageGroups[ageGroup as keyof typeof ageGroups],
count: count || null
})).reverse();
diff block
greptile
logic: Missing null check for results from multi.exec() which could be null if transaction fails
suggested fix
const results = await multi.exec()
+ if (!results) {
+ throw new Error('Redis transaction failed')
}
const scardResult = ttlSeconds ? results[2] : results[1]
return scardResult[1]
diff block
greptile
logic: Missing null check for instance.config['authed_user'] - could throw KeyError
suggested fix
+ if "authed_user" not in instance.config:
+ raise ValidationError("Missing authed_user in integration config")
authed_user: str = instance.config["authed_user"]["id"]
diff block
greptile
logic: missing null check for chunk.textDelta like in text-delta case. Could cause issues if textDelta is undefined
suggested fix
case "reasoning": {
+ if (!chunk.textDelta) break; // ignore empty text deltas
controller.enqueue({
type: AssistantStreamChunkType.ReasoningDelta,
value: chunk.textDelta,
});
break;
}
diff block
greptile
logic: Missing null check for cloudRef.current could cause runtime errors
suggested fix
const cloud = this.cloudRef.current;
+ if (!cloud) throw new Error('Cloud reference is not initialized');
diff block
greptile
logic: Missing null checks on children array access could cause runtime errors if the expected structure is not present
diff block
greptile
logic: Missing null check for `change` parameter. Other handlers in this file check if change exists before accessing properties.
suggested fix
api_token: (change) => {
+ if (!change) {
return null
}
+ const after = change.after
if (after === undefined) {
return null
}
diff block
greptile
logic: Missing null check for txDetails.meta.innerInstructions[0] could cause runtime errors if transaction has no inner instructions
suggested fix
+ if (!txDetails.meta?.innerInstructions?.[0]?.instructions) {
+ throw new Error('Transaction has no inner instructions');
+ }
const innerInstructions = txDetails.meta.innerInstructions[0].instructions;
diff block
greptile
logic: Missing null checks on question parameters could cause NullPointerException if array is empty
suggested fix
String[] givenAnswers = {
+ question_0_solution != null && question_0_solution.length > 0 ? question_0_solution[0] : "",
+ question_1_solution != null && question_1_solution.length > 0 ? question_1_solution[0] : "",
+ question_2_solution != null && question_2_solution.length > 0 ? question_2_solution[0] : "",
+ question_3_solution != null && question_3_solution.length > 0 ? question_3_solution[0] : "",
+ question_4_solution != null && question_4_solution.length > 0 ? question_4_solution[0] : ""
};
diff block
greptile
logic: Missing null check for event parameter and validation for negative quantity
suggested fix
public CartItem(Event event, int quantity) {
+ if (event == null) {
+ throw new IllegalArgumentException("Event cannot be null");
}
+ if (quantity < 0) {
+ throw new IllegalArgumentException("Quantity cannot be negative");
}
this.event = event;
this.quantity = quantity;
}
diff block
greptile
logic: Missing null check before adding order to list
diff block
greptile
logic: missing null check before adding order to list
suggested fix
public void addOrder(Order order) {
+ if (order != null) {
orders.add(order);
}
}
diff block
greptile
logic: missing null check for cart and paymentMethod parameters
diff block
greptile
logic: Missing null check on credentialsToRevoke[activeIndex]. Could throw if array is empty.
suggested fix
+ if (!credentialsToRevoke?.[activeIndex]?.password) {
+ throw new Error('No active credentials found to revoke');
+ }
const currentPassword = credentialsToRevoke[activeIndex].password;
diff block
greptile
logic: Missing null check for subscriber after findOne() - could cause runtime error if subscriber not found
```suggestion
const subscriber = await pkiSubscriberDAL.findOne({
name: subscriberName,
projectId
});
+ if (!subscriber) throw new NotFoundError({ message: `PKI subscriber named '${subscriberName}' not found` });
```
diff block
greptile
logic: Missing null check for marketData parameter before validation
suggested fix
public async Task<string> PublishMarketDataAsync(T marketData)
{
+ if (marketData == null)
{
+ throw new ArgumentNullException(nameof(marketData));
}
diff block
greptile
logic: Missing null check for secretName parameter
suggested fix
private async Task<string> GetSecretAsync(string secretName)
{
+ if (string.IsNullOrEmpty(secretName))
+ throw new ArgumentException("Secret name cannot be null or empty", nameof(secretName));
diff block
greptile
logic: Missing null check for data parameter. Could throw NullReferenceException.
suggested fix
public void Validate(CryptoOrdinalSpotPriceData data)
{
+ if (data == null)
+ throw new ValidationException("Data cannot be null.");
diff block
greptile
logic: Missing null check before using mountPoint. If mountPoint is null, this will try to open "null" as a path.
```suggestion
+ if (!this.mountPoint) {
+ throw new Error("No mount point available");
}
await Disk.execCommand(`open "${this.mountPoint}"`);
```
diff block
greptile
logic: Missing null checks on parseInt calls - could return NaN if value is undefined
suggested fix
gameData.bggId = result?.items?.item?._attributes?.objectid;
gameData.title = result?.items?.item.name?._text;
gameData.img = result?.items?.item?.thumbnail?._text;
gameData.description = result?.items?.item?.description?._text;
+ gameData.minPlayers = result?.items?.item?.minplayers?._attributes?.value ? parseInt(result.items.item.minplayers._attributes.value) : undefined;
+ gameData.maxPlayers = result?.items?.item?.maxplayers?._attributes?.value ? parseInt(result.items.item.maxplayers._attributes.value) : undefined;
+ gameData.avgPlaytime = result?.items?.item?.playingtime?._attributes?.value ? parseInt(result.items.item.playingtime._attributes.value) : undefined;
diff block
greptile
logic: missing null check for currentMetric and its chart_config property could cause runtime errors
```suggestion
const currentMetric = getMetricMemoized({ metricId });
+ if (!currentMetric?.chart_config) {
+ throw new Error(`Invalid metric or chart config for id: ${metricId}`);
}
```
diff block
greptile
logic: Missing null check for articleType in tag value could cause undefined to display
diff block
greptile
logic: missing null check for MAPPING[name] - could crash if name not found in mapping
diff block
greptile
logic: Missing null check here. If sync_time_of_day is None, this could lead to unexpected behavior when a user clears the field.
suggested fix
+ if sync_time_of_day is not None:
if sync_time_of_day != instance.sync_time_of_day:
was_sync_time_of_day_updated = True
validated_data["sync_time_of_day"] = sync_time_of_day
instance.sync_time_of_day = sync_time_of_day
diff block
greptile
logic: Missing null check on res.data and res.data.items before accessing. Could throw runtime error if API returns unexpected response structure.
suggested fix
+ if (res?.data?.items) {
setRoles(res.data.items);
return;
} else {
diff block
greptile
logic: Missing null check for response.data.data.user - could throw if user not found
suggested fix
+ const calendarData = response.data?.data?.user?.contributionsCollection?.contributionCalendar;
diff block
greptile
logic: Missing null check for msg.content.image_url before accessing it as a string
suggested fix
+ if (msg.content?.image_url && typeof msg.content.image_url === "string") {
return {
role: msg.role,
_type: "image",
content: msg.content.text || "",
image_url: msg.content.image_url,
};
diff block
greptile
logic: Missing null check for trip.legs[0] - could throw if trip.legs is empty array
suggested fix
+ const fromStationName: string | undefined = trip.legs.length > 0 ? trip.legs[0].origin.name : undefined;
diff block
greptile
logic: Missing null check before non-null assertion (!). getElementById('root') could return null
suggested fix
+const rootElement = document.getElementById('root');
+if (!rootElement) throw new Error('Root element not found');
+createRoot(rootElement).render(
Want to avoid this bug in your codebase? Try Greptile.
Avoid this bug!