10 examples

Missing default case

Switch statement missing fallback option, causing potential errors.

[ FAQ1 ]

What is a missing default case?

A missing default case occurs in a switch statement when no explicit default branch is provided to handle cases not matched by existing case conditions. Without a default case, unanticipated input values cause the switch statement to skip handling, potentially leading to undefined or unexpected program behavior. Compilers, linters, or static analysis tools typically flag this as a warning or error, highlighting insufficient code coverage or missing logic paths. Properly handling all potential scenarios is critical to preventing bugs and maintaining predictable control flow.
[ FAQ2 ]

How to fix a missing default case

To fix a missing default case, explicitly add a default branch to your switch statements, ensuring all unanticipated or unspecified cases are handled gracefully. The default case should manage unexpected inputs, either through error logging, fallback values, or clear exception handling. Employ linters and static analysis tools that automatically detect and warn about missing default cases, encouraging consistent and thorough code coverage. Regularly review and test your switch logic to guarantee completeness and correctness of your control flow.
diff block
}
export const getDefaultMetricTitle = (metric: ExperimentMetric): string => {
- if (metric.metric_config.kind === NodeKind.ExperimentEventMetricConfig) {
- return metric.metric_config.event
- } else if (metric.metric_config.kind === NodeKind.ExperimentActionMetricConfig) {
- return metric.metric_config.name || `Action ${metric.metric_config.action}`
+ const getDefaultName = (
+ entity: EventsNode | ActionsNode | ExperimentDataWarehouseNode
+ ): string | null | undefined => {
+ if (entity.kind === NodeKind.EventsNode) {
+ return entity.name || entity.event
+ } else if (entity.kind === NodeKind.ActionsNode) {
+ return entity.name || `Action ${entity.id}`
+ } else if (entity.kind === NodeKind.ExperimentDataWarehouseNode) {
+ return entity.table_name
+ }
+ }
+
+ switch (metric.metric_type) {
+ case ExperimentMetricType.MEAN:
+ return getDefaultName(metric.source) || 'Untitled metric'
+ case ExperimentMetricType.FUNNEL:
+ return getDefaultName(metric.series[0]) || 'Untitled funnel'
}
Greptile
greptile
logic: Missing default case in switch; potential undefined return for unhandled metric types.
suggested fix
switch (metric.metric_type) {
case ExperimentMetricType.MEAN:
return getDefaultName(metric.source) || 'Untitled metric'
case ExperimentMetricType.FUNNEL:
return getDefaultName(metric.series[0]) || 'Untitled funnel'
+ default:
+ return 'Untitled metric'
}
diff block
{(() => {
switch (groupByType) {
case 'project':
- return <ProductivityProjectTable data={activityReport} isLoading={loadingActivityReport} />;
+ return <ProductivityProjectTable data={activityReport} isLoading={loading} />;
case 'date':
- return <ProductivityTable data={activityReport} isLoading={loadingActivityReport} />;
+ return <ProductivityTable data={activityReport} isLoading={loading} />;
case 'employee':
- return (
- <ProductivityEmployeeTable data={activityReport} isLoading={loadingActivityReport} />
- );
+ return <ProductivityEmployeeTable data={activityReport} isLoading={loading} />;
case 'application':
- return (
- <ProductivityApplicationTable data={activityReport} isLoading={loadingActivityReport} />
- );
+ return <ProductivityApplicationTable data={activityReport} isLoading={loading} />;
}
})()}
Greptile
greptile
logic: Missing default case in switch statement could lead to undefined render if groupByType has unexpected value
diff block
+import { useBus, useFerry, useMetro, useShip, useTram } from "../fetchers/departures";
+import { List, Icon, Color, ActionPanel, Action, showToast, Toast } from "@raycast/api";
+import { TransportMode } from "../types/TransportMode";
+import { Site as SiteType } from "../types/Site";
+import moment from "moment";
+
+const getMetroLine = (lineId: number) => {
+ switch (lineId) {
+ case 10:
+ case 11:
+ return {
+ color: Color.Blue,
+ name: "Blue Line",
+ };
+ case 13:
+ case 14:
+ return {
+ color: Color.Red,
+ name: "Red Line",
+ };
+ case 17:
+ case 18:
+ case 19:
+ return {
+ color: Color.Green,
+ name: "Green Line",
+ };
+ }
+};
+
+const getIcon = (transportMode: TransportMode) => {
+ switch (transportMode) {
+ case TransportMode.Bus:
+ return Icon.Car;
+ case TransportMode.Metro:
+ case TransportMode.Tram:
+ return Icon.Train;
+ case TransportMode.Ferry:
+ case TransportMode.Ship:
+ return Icon.Boat;
+ }
+};
Greptile
greptile
logic: Missing default case in switch statement. Train transport mode not handled.
diff block
+import { Image } from "@raycast/api";
+import { Property, PropertyFormat, RawProperty, RawTag, Tag } from "../models";
+import { colorToHex } from "../utils";
+
+export function mapProperties(properties: RawProperty[]): Property[] {
+ return properties.map((property) => {
+ return mapProperty(property);
+ });
+}
+
+export function mapProperty(property: RawProperty): Property {
+ return {
+ ...property,
+ name: property.name?.trim() || "Untitled",
+ icon: getIconForProperty(property.format),
+ };
+}
+
+export function getIconForProperty(format: PropertyFormat): Image.ImageLike {
+ const tintColor = { light: "grey", dark: "grey" };
+ switch (format) {
+ case PropertyFormat.Text:
+ return { source: "icons/property/text.svg", tintColor: tintColor };
+ case PropertyFormat.Number:
+ return { source: "icons/property/number.svg", tintColor: tintColor };
+ case PropertyFormat.Select:
+ return { source: "icons/property/select.svg", tintColor: tintColor };
+ case PropertyFormat.MultiSelect:
+ return { source: "icons/property/multi_select.svg", tintColor: tintColor };
+ case PropertyFormat.Date:
+ return { source: "icons/property/date.svg", tintColor: tintColor };
+ case PropertyFormat.Files:
+ return { source: "icons/property/files.svg", tintColor: tintColor };
+ case PropertyFormat.Checkbox:
+ return { source: "icons/property/checkbox.svg", tintColor: tintColor };
+ case PropertyFormat.Url:
+ return { source: "icons/property/url.svg", tintColor: tintColor };
+ case PropertyFormat.Email:
+ return { source: "icons/property/email.svg", tintColor: tintColor };
+ case PropertyFormat.Phone:
+ return { source: "icons/property/phone.svg", tintColor: tintColor };
+ case PropertyFormat.Objects:
+ return { source: "icons/property/objects.svg", tintColor: tintColor };
+ }
+}
Greptile
greptile
logic: Missing default case in switch statement. Could return undefined if format is not handled. Add a default case to handle unknown property formats.
suggested fix
export function getIconForProperty(format: PropertyFormat): Image.ImageLike {
const tintColor = { light: "grey", dark: "grey" };
switch (format) {
case PropertyFormat.Text:
return { source: "icons/property/text.svg", tintColor: tintColor };
case PropertyFormat.Number:
return { source: "icons/property/number.svg", tintColor: tintColor };
case PropertyFormat.Select:
return { source: "icons/property/select.svg", tintColor: tintColor };
case PropertyFormat.MultiSelect:
return { source: "icons/property/multi_select.svg", tintColor: tintColor };
case PropertyFormat.Date:
return { source: "icons/property/date.svg", tintColor: tintColor };
case PropertyFormat.Files:
return { source: "icons/property/files.svg", tintColor: tintColor };
case PropertyFormat.Checkbox:
return { source: "icons/property/checkbox.svg", tintColor: tintColor };
case PropertyFormat.Url:
return { source: "icons/property/url.svg", tintColor: tintColor };
case PropertyFormat.Email:
return { source: "icons/property/email.svg", tintColor: tintColor };
case PropertyFormat.Phone:
return { source: "icons/property/phone.svg", tintColor: tintColor };
case PropertyFormat.Objects:
return { source: "icons/property/objects.svg", tintColor: tintColor };
+ default:
return { source: "icons/property/text.svg", tintColor: tintColor };
}
}
diff block
-import { actions, kea, listeners, path, reducers, selectors } from 'kea'
+import { actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
-import { ErrorTrackingIssueAssignee } from '~/queries/schema/schema-general'
-import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
+import { FilterLogicalOperator } from '~/types'
-import type { errorTrackingAutoAssignmentLogicType } from './errorTrackingAutoAssignmentLogicType'
+import type { errorTrackingRulesLogicType } from './errorTrackingRulesLogicType'
+import { ErrorTrackingRule, ErrorTrackingRuleNew, ErrorTrackingRulesLogicProps, ErrorTrackingRuleType } from './types'
-export type ErrorTrackingAssignmentRule = {
- id: string
- assignee: ErrorTrackingIssueAssignee | null
- filters: UniversalFiltersGroup
+function createNewRule<T extends ErrorTrackingRuleType>(ruleType: T): ErrorTrackingRuleNew {
+ if (ruleType == ErrorTrackingRuleType.Assignment || ruleType == ErrorTrackingRuleType.Grouping) {
+ return {
+ id: 'new',
+ assignee: null,
+ filters: { type: FilterLogicalOperator.Or, values: [] },
+ }
+ } else if (ruleType == ErrorTrackingRuleType.Suppression) {
+ return {
+ id: 'new',
+ filters: { type: FilterLogicalOperator.Or, values: [] },
+ }
+ }
+ throw new Error('Unsupported rule type')
}
Greptile
greptile
logic: createNewRule function needs exhaustive type checking - missing default case in switch statement could cause runtime errors with new rule types ```suggestion +function createNewRule(ruleType: ErrorTrackingRuleType): ErrorTrackingRuleNew { + switch (ruleType) { + case 'assignment_rules': return { id: 'new', assignee: null, filters: { type: FilterLogicalOperator.Or, values: [] }, } + case 'suppression_rules': return { id: 'new', filters: { type: FilterLogicalOperator.Or, values: [] }, } + default: + throw new Error(`Unsupported rule type: ${ruleType}`) } } ```
diff block
Error = 8,
}
-function getSeverityString(
+export function getSeverityString(
severity: MarkerSeverity
): YamlValidationErrorSeverity {
- if (severity === MarkerSeverity.Error) {
- return "error";
+ switch (severity) {
+ case MarkerSeverity.Error:
+ return "error";
+ case MarkerSeverity.Warning:
+ return "warning";
+ case MarkerSeverity.Info:
+ return "info";
+ case MarkerSeverity.Hint:
+ return "hint";
}
Greptile
greptile
logic: Missing default case in switch could return undefined. Consider adding a default fallback.
diff block
+import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
+import { QueryBus } from '@nestjs/cqrs';
-export class JwtDefaultGuard extends AuthGuard('registeredUserJWT') {}
+import { ICommandResponse } from '@common/types/command-response.type';
+import { ROLE } from '@libs/contracts/constants';
+
+import { GetAdminByUsernameQuery } from '@modules/admin/queries/get-admin-by-username';
+import { GetTokenByUuidQuery } from '@modules/api-tokens/queries/get-token-by-uuid';
+import { ApiTokenEntity } from '@modules/api-tokens/entities/api-token.entity';
+import { AdminEntity } from '@modules/admin/entities/admin.entity';
+import { IJWTAuthPayload } from '@modules/auth/interfaces';
+@Injectable()
+export class JwtDefaultGuard extends AuthGuard('registeredUserJWT') {
+ constructor(private readonly queryBus: QueryBus) {
+ super();
+ }
+
+ async canActivate(context: ExecutionContext): Promise<boolean> {
+ const isJwtValid = await super.canActivate(context);
+ if (!isJwtValid) {
+ return false;
+ }
+
+ const { user } = context.switchToHttp().getRequest<{ user: IJWTAuthPayload }>();
+
+ if (!user || !user.role || !user.uuid) {
+ return false;
+ }
+
+ switch (user.role) {
+ case ROLE.API: {
+ const token = await this.getTokenByUuid({ uuid: user.uuid });
+ if (!token.isOk) {
+ return false;
+ }
+ return true;
+ }
+ case ROLE.ADMIN: {
+ if (!user.username) {
+ return false;
+ }
+
+ const adminEntity = await this.getAdminByUsername({
+ username: user.username,
+ role: user.role,
+ });
+
+ if (!adminEntity.isOk || !adminEntity.response) {
+ return false;
+ }
+
+ if (adminEntity.response.uuid !== user.uuid) {
+ return false;
+ }
+ break;
+ }
+ }
Greptile
greptile
logic: Missing default case in switch statement could allow unauthorized access for unknown roles
suggested fix
switch (user.role) {
case ROLE.API: {
const token = await this.getTokenByUuid({ uuid: user.uuid });
if (!token.isOk) {
return false;
}
return true;
}
case ROLE.ADMIN: {
if (!user.username) {
return false;
}
const adminEntity = await this.getAdminByUsername({
username: user.username,
role: user.role,
});
if (!adminEntity.isOk || !adminEntity.response) {
return false;
}
if (adminEntity.response.uuid !== user.uuid) {
return false;
}
return true;
}
+ default:
return false;
}
diff block
export class FileProviderService {
constructor(private prisma: PrismaService) {}
+ rpcToPrismaProvider(req: FileProviderProto.ProviderType): FileProviderType {
+ switch (req) {
+ case FileProviderProto.ProviderType.S3:
+ return 'S3';
+ case FileProviderProto.ProviderType.AZURE:
+ return 'AZURE';
+ }
+ }
Greptile
greptile
logic: Missing default case in switch statement could return undefined for unknown provider types ```suggestion rpcToPrismaProvider(req: FileProviderProto.ProviderType): FileProviderType { switch (req) { case FileProviderProto.ProviderType.S3: return 'S3'; case FileProviderProto.ProviderType.AZURE: return 'AZURE'; + default: + throw new Error(`Unsupported provider type: ${req}`); } } ```
diff block
{(() => {
switch (groupByType) {
case 'project':
- return <ProductivityProjectTable data={activityReport} isLoading={loadingActivityReport} />;
+ return <ProductivityProjectTable data={activityReport} isLoading={loading} />;
case 'date':
- return <ProductivityTable data={activityReport} isLoading={loadingActivityReport} />;
+ return <ProductivityTable data={activityReport} isLoading={loading} />;
case 'employee':
- return (
- <ProductivityEmployeeTable data={activityReport} isLoading={loadingActivityReport} />
- );
+ return <ProductivityEmployeeTable data={activityReport} isLoading={loading} />;
case 'application':
- return (
- <ProductivityApplicationTable data={activityReport} isLoading={loadingActivityReport} />
- );
+ return <ProductivityApplicationTable data={activityReport} isLoading={loading} />;
}
})()}
Greptile
greptile
style: missing default case in switch statement could lead to undefined being rendered
suggested fix
+ {(() => {
+ switch (groupByType) {
+ case 'project':
return <ProductivityProjectTable data={activityReport} isLoading={loading} />;
+ case 'date':
return <ProductivityTable data={activityReport} isLoading={loading} />;
+ case 'employee':
return <ProductivityEmployeeTable data={activityReport} isLoading={loading} />;
+ case 'application':
return <ProductivityApplicationTable data={activityReport} isLoading={loading} />;
+ default:
return <ProductivityTable data={activityReport} isLoading={loading} />;
+ }
+ })()}
diff block
+import { useBus, useFerry, useMetro, useShip, useTram } from "../fetchers/departures";
+import { List, Icon, Color, ActionPanel, Action, showToast, Toast } from "@raycast/api";
+import { TransportMode } from "../types/TransportMode";
+import { Site as SiteType } from "../types/Site";
+import moment from "moment";
+
+const getMetroLine = (lineId: number) => {
+ switch (lineId) {
+ case 10:
+ case 11:
+ return {
+ color: Color.Blue,
+ name: "Blue Line",
+ };
+ case 13:
+ case 14:
+ return {
+ color: Color.Red,
+ name: "Red Line",
+ };
+ case 17:
+ case 18:
+ case 19:
+ return {
+ color: Color.Green,
+ name: "Green Line",
+ };
+ }
+};
Greptile
greptile
logic: Missing default case in switch statement. Unknown metro line IDs will return undefined. ```suggestion const getMetroLine = (lineId: number) => { switch (lineId) { case 10: case 11: return { color: Color.Blue, name: "Blue Line", }; case 13: case 14: return { color: Color.Red, name: "Red Line", }; case 17: case 18: case 19: return { color: Color.Green, name: "Green Line", }; + default: return { + color: Color.PrimaryText, + name: `Line ${lineId}`, }; } }; ```