23 examples
Unhandled promise
Promises without proper handling, causing silent failures.
[ FAQ1 ]
What is an unhandled promise?
An unhandled promise occurs in JavaScript when a promise is rejected, but the rejection isn't caught or explicitly handled by a
.catch()
method or equivalent error-handling logic. This situation results in runtime warnings like "UnhandledPromiseRejection" and may cause unexpected application behavior or silent failures. Ignoring rejected promises can mask underlying issues, degrade user experience, and complicate debugging and maintenance efforts in asynchronous JavaScript code.[ FAQ2 ]
How to fix unhandled promise rejections
To fix unhandled promise rejections, always attach a
.catch()
handler to promises, or use async functions wrapped in try-catch
blocks to manage errors explicitly. Employ global event handlers like window.onunhandledrejection
to log and handle any promise rejections not managed locally. Ensure thorough error handling at each step of asynchronous workflows, clearly propagating errors up the chain as necessary. Regularly monitor and review runtime warnings, systematically resolving any unhandled promises to maintain stable and reliable JavaScript applications.diff block
greptile
logic: Missing await on async operation - could cause race conditions or unhandled promise rejections
suggested fix
+ await InvoiceService.createInvoiceFromStripe({
sb,
stripeInvoice: invoice,
internalCustomerId: activeCusProducts[0].internal_customer_id,
productIds: activeCusProducts.map((p) => p.product_id),
internalProductIds: activeCusProducts.map((p) => p.internal_product_id),
org: org,
});
diff block
greptile
style: Missing try/catch block around unzipFile call. Unhandled promise rejection could crash the app.
diff block
greptile
logic: onTogglePin is async but used without await, could lead to unhandled promise rejection
suggested fix
onAction={async () => {
try {
+ await onTogglePin(rule);
} catch (error) {
+ showFailureToast("Failed to toggle pin", error);
}
}}
shortcut={{ modifiers: ["cmd"], key: "i" }}
diff block
greptile
logic: navigator.clipboard.writeText() can fail - should handle the promise rejection case to prevent unhandled promise rejections
suggested fix
navigator.clipboard.writeText(value).then(() => {
setIsCopied(true);
setTimeout(() => setIsCopied(false), copiedDuration);
+ }).catch((error) => {
+ console.error('Failed to copy text:', error);
});
};
diff block
greptile
style: handleFirstLoad should catch errors from the load functions to prevent unhandled promise rejections
suggested fix
const handleFirstLoad = useCallback(async () => {
+ try {
await loadAllDayPlans();
await loadMyDailyPlans();
await loadEmployeeDayPlans();
firstLoadDailyPlanData();
+ } catch (error) {
+ console.error('Error during first load:', error);
+ }
}, [firstLoadDailyPlanData, loadAllDayPlans, loadEmployeeDayPlans, loadMyDailyPlans]);
diff block
greptile
logic: Re-throwing error after setting error state may cause unhandled promise rejection
```suggestion
+ toast.error(`Failed to download model: ${errorMessage}`)
```
diff block
greptile
style: Consider handling potential errors from AssistantMessageStream.fromAssistantStream() to prevent unhandled promise rejections
suggested fix
+ try {
+ const messageStream = AssistantMessageStream.fromAssistantStream(stream);
+ for await (const result of messageStream) {
diff block
greptile
logic: shutdown() should be in a try/catch block to prevent potential unhandled promise rejections
suggested fix
export const handleError = async ({ error, status }: HandleServerError) => {
if (status !== 404) {
captureException(error);
+ try {
await shutdown();
+ } catch (shutdownError) {
+ console.error('Failed to shutdown PostHog client:', shutdownError);
}
}
}
diff block
greptile
logic: Missing error handling for main(). Unhandled promise rejection could crash the process.
suggested fix
+main().catch(err => {
+ console.error('Failed to clone repository:', err);
+ process.exit(1);
});
diff block
greptile
logic: Missing error handling if params Promise rejects - could cause unhandled promise rejection
diff block
greptile
style: potential unhandled promise rejection if onAction() fails
diff block
greptile
logic: Error is thrown after showing toast, which may lead to unhandled promise rejection in parent components
diff block
greptile
logic: No error handling for createOidcProvider failure. Could cause unhandled promise rejection.
```suggestion
+ try {
const oidc = await createOidcProvider({
id: "stack-preconfigured-idp:integrations/custom",
baseUrl: idpBaseUrl.toString(),
clientInteractionUrl: new URL(`/integrations/custom/confirm`, getEnvVariable("NEXT_PUBLIC_STACK_DASHBOARD_URL")).toString(),
});
return oidc.callback();
+ } catch (error) {
+ console.error('Failed to create OIDC provider:', error);
+ throw error;
+ }
```
diff block
greptile
logic: Optional chaining on createIssueType could result in unhandled promise rejection if function returns undefined
diff block
greptile
logic: The rename method lacks error handling try/catch block unlike delete and upload methods. This could cause unhandled promise rejections.
suggested fix
async rename(imageName: string, newName: string): Promise<void> {
+ try {
const projectFolder = this.projectsManager.project?.folderPath;
if (!projectFolder) {
console.error('Failed to rename image, projectFolder not found');
return;
}
await invokeMainChannel<string, string>(
MainChannels.RENAME_IMAGE_IN_PROJECT,
projectFolder,
imageName,
newName,
);
this.scanImages();
+ } catch (error) {
+ console.error('Error renaming image:', error);
+ throw error;
}
}
diff block
greptile
style: Consider handling the error here instead of re-throwing it, as this could lead to an unhandled promise rejection if the caller doesn't have a catch block.
Want to avoid this bug in your codebase? Try Greptile.
Avoid this bug!