You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS Code扩展开发:解决1秒内未处理的Promise拒绝报错

Fixing "Rejected Promise Not Handled Within 1 Second" in Your VS Code Rename Extension

Hey there! Let's break down and fix that annoying promise rejection error you're hitting. The root issue here is that vscode.commands.executeCommand returns a Promise, and when that Promise rejects (say, if there's no valid symbol to rename at your cursor position, or the rename provider encounters an error), your code isn't catching that rejection. VS Code alerts you about unhandled promise rejections with that 1-second warning.

Here's how to fix this step by step:

1. Add Proper Promise Error Handling

Instead of letting the Promise float unhandled, wrap it in a try/catch block (using async/await for cleaner code) or attach a .catch() handler. This will catch any rejections and let you handle them gracefully.

2. Ensure Your Command Parameters Are Complete

Looking at your code snippet, you cut off the final argument for executeDocumentRenameProvider — this command requires three parameters:

  • The document URI
  • The cursor position (for the symbol to rename)
  • The new name string you want to use

3. Apply the Workspace Edit

The executeDocumentRenameProvider command returns a WorkspaceEdit object, but it doesn't apply the edit automatically. You need to call vscode.workspace.applyEdit() to make the change happen in the editor.

Corrected Code Example

Here's a polished version of your code that addresses all these points:

async function renameSelectedSymbol(newName: string) {
  // Check for an active editor first (no need to throw an uncaught error!)
  const editor = vscode.window.activeTextEditor;
  if (!editor) {
    vscode.window.showErrorMessage("Oops, no active text editor found!");
    return;
  }

  const position = editor.selection.active;
  const uri = editor.document.uri;

  try {
    // Execute the rename provider and get the workspace edit
    const renameEdit = await vscode.commands.executeCommand<vscode.WorkspaceEdit>(
      "vscode.executeDocumentRenameProvider",
      uri,
      position,
      newName
    );

    // Apply the edit only if it's valid and not empty
    if (renameEdit && !renameEdit.isEmpty) {
      await vscode.workspace.applyEdit(renameEdit);
      vscode.window.showInformationMessage(`Successfully renamed to ${newName}!`);
    } else {
      vscode.window.showErrorMessage("Couldn't find a renameable symbol at your cursor position.");
    }
  } catch (error) {
    // Log the error for debugging and show a user-friendly message
    console.error("Rename failed:", error);
    vscode.window.showErrorMessage(`Rename failed: ${(error as Error).message}`);
  }
}

// Register your command with async support
export function activate(context: vscode.ExtensionContext) {
  let disposable = vscode.commands.registerCommand('your-extension-name.renameSelected', async () => {
    // Let the user input the new name first
    const newName = await vscode.window.showInputBox({
      prompt: "Enter the new name for the selected symbol",
      placeHolder: "E.g., myNewVariable",
      validateInput: (value) => {
        return value.trim() ? undefined : "Please enter a non-empty name";
      }
    });

    // Only run the rename if the user provided a name
    if (newName) {
      await renameSelectedSymbol(newName.trim());
    }
  });

  context.subscriptions.push(disposable);
}

Key Improvements

  • Error Handling: The try/catch block catches any promise rejections from executeCommand and handles them with user feedback and console logging.
  • User Experience: We prompt the user for a new name with input validation, and show clear success/error messages instead of silent failures.
  • Safety Checks: We verify the active editor exists, and only apply the edit if it's valid (avoiding empty or invalid edits).
  • Proper API Usage: We complete the executeDocumentRenameProvider parameters and explicitly apply the workspace edit.

Additional Tips

  • Make sure the cursor is positioned on a valid, renameable symbol (like a variable, function, or class name) when running the command — if it's not, the rename provider will reject the promise, which your catch block will handle.
  • Test edge cases (no active editor, empty name input) to ensure your extension behaves predictably.

内容的提问来源于stack exchange,提问作者Antha On Twitch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:59:30