Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use String(err) instead #428

Closed
wants to merge 5 commits into from
Closed

Use String(err) instead #428

wants to merge 5 commits into from

Conversation

Shougo
Copy link
Contributor

@Shougo Shougo commented Nov 22, 2024

Test.

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced error handling logic for clearer and more contextual error messages.
    • Improved formatting of error messages based on error types for better clarity.
    • Updated test cases to ensure consistent formatting of error messages.

@Shougo Shougo requested a review from lambdalisue November 22, 2024 00:39
Copy link

coderabbitai bot commented Nov 22, 2024

Walkthrough

The changes made in this pull request focus on improving the error handling logic within the call method of the Plugin class in the denops/@denops-private/service.ts file. The modification involves replacing the error message extraction with a new function that formats the error based on its type, enhancing the clarity of error messages. Additionally, a normalization function was introduced in the test suite for denops#request_async(), ensuring consistent error message formatting. No alterations were made to the public interface, method signatures, or overall structure of the classes, ensuring that the functionality remains unchanged.

Changes

File Change Summary
denops/@denops-private/service.ts Modified error handling in the call method of the Plugin class to use a new message function for error formatting, improving clarity. No changes to public interfaces or method signatures.
tests/denops/runtime/functions/denops/request_async_test.ts Added normalizeMessage function to improve error message consistency in tests. Updated assertions to utilize the new normalization function.

Poem

In the code where errors play,
A rabbit hops and finds a way.
With strings now clear, no checks to fear,
The messages shine, oh what a cheer!
Simplified paths, we dance and sway,
In the world of code, we’ll hop away! 🐇✨

Warning

Rate limit exceeded

@Shougo has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 25 minutes and 6 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between b01eb12 and 67761d5.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b01eb12 and 67761d5.

📒 Files selected for processing (1)
  • tests/denops/runtime/functions/denops/request_async_test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/denops/runtime/functions/denops/request_async_test.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8535c11 and 715ef4d.

📒 Files selected for processing (1)
  • tests/denops/runtime/functions/denops/request_async_test.ts (1 hunks)
🔇 Additional comments (2)
tests/denops/runtime/functions/denops/request_async_test.ts (2)

132-135: LGTM! Clear and focused type definition.

The ErrorEvent type correctly defines the structure needed for error handling with appropriate properties.


Line range hint 148-163: LGTM! Test assertion properly handles error normalization.

The test correctly uses the new normalizeMessage function and has appropriate expectations for the error message format.

Comment on lines 136 to 144
const normalizeMessage = (events: unknown[]) => {
return events.map(event => {
const error = (event as unknown[])[1] as ErrorEvent[];
if (error[0]?.message) {
error[0].message = error[0].message.replace(/\n.*/g, '');
}
return event;
});
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve type safety and immutability in normalizeMessage function.

The current implementation has several potential issues:

  1. Unsafe type assertions without proper checks
  2. Potential null reference when accessing error[0]
  3. Mutates the input array instead of creating a new one

Consider this safer implementation:

-const normalizeMessage = (events: unknown[]) => {
-  return events.map(event => {
-    const error = (event as unknown[])[1] as ErrorEvent[];
-    if (error[0]?.message) {
-      error[0].message = error[0].message.replace(/\n.*/g, '');
-    }
-    return event;
-  });
+const normalizeMessage = (events: unknown[]): unknown[] => {
+  return events.map(event => {
+    if (!Array.isArray(event) || event.length < 2) {
+      return event;
+    }
+    const errors = event[1];
+    if (!Array.isArray(errors) || errors.length === 0) {
+      return event;
+    }
+    return [
+      event[0],
+      errors.map(error => ({
+        ...error,
+        message: error?.message?.replace(/\n.*/g, '') ?? error?.message
+      }))
+    ];
+  });
};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const normalizeMessage = (events: unknown[]) => {
return events.map(event => {
const error = (event as unknown[])[1] as ErrorEvent[];
if (error[0]?.message) {
error[0].message = error[0].message.replace(/\n.*/g, '');
}
return event;
});
};
const normalizeMessage = (events: unknown[]): unknown[] => {
return events.map(event => {
if (!Array.isArray(event) || event.length < 2) {
return event;
}
const errors = event[1];
if (!Array.isArray(errors) || errors.length === 0) {
return event;
}
return [
event[0],
errors.map(error => ({
...error,
message: error?.message?.replace(/\n.*/g, '') ?? error?.message
}))
];
});
};

Copy link

codecov bot commented Nov 24, 2024

Codecov Report

Attention: Patch coverage is 50.00000% with 6 lines in your changes missing coverage. Please review.

Project coverage is 95.23%. Comparing base (0c72261) to head (67761d5).

Files with missing lines Patch % Lines
denops/@denops-private/service.ts 50.00% 6 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #428      +/-   ##
==========================================
- Coverage   95.55%   95.23%   -0.32%     
==========================================
  Files          25       25              
  Lines        1418     1428      +10     
  Branches      180      181       +1     
==========================================
+ Hits         1355     1360       +5     
- Misses         60       65       +5     
  Partials        3        3              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@lambdalisue
Copy link
Member

lambdalisue commented Nov 25, 2024

Could you show an example error message that shows stacktrace in PR body?

@Shougo
Copy link
Contributor Author

Shougo commented Nov 25, 2024

Before:

"Failed to call 'not_exist_method' API in 'dummy': TypeError: this[#denops].dispatcher[fn] is not a function"

After:

"Failed to call 'not_exist_method' API in 'dummy': TypeError: this[#denops].dispatcher[fn] is not a function\n" +
"    at Plugin.call (file:///home/shougo/work/denops.vim/denops/@denops-private/service.ts:276:47)\n" +
"    at Service.#dispatch (file:///home/shougo/work/denops.vim/denops/@denops-private/service.ts:117:25)\n" +
"    at Service.dispatchAsync (file:///home/shougo/work/denops.vim/denops/@denops-private/service.ts:141:37)\n" +
"    at invoke (file:///home/shougo/work/denops.vim/denops/@denops-private/host.ts:92:22)\n" +
"    at Object.invoke (file:///home/shougo/work/denops.vim/denops/@denops-private/host/nvim.ts:34:16)\n" +
"    at dispatch (https://jsr.io/@lambdalisue/messagepack-rpc/2.4.0/dispatcher.ts:36:36)\n" +
"    at Session.#dispatch (https://jsr.io/@lambdalisue/messagepack-rpc/2.4.0/session.ts:255:28)\n" +
"    at Session.#handleNotificationMessage (https://jsr.io/@lambdalisue/messagepack-rpc/2.4.0/session.ts:310:45)\n" +
"    at Session.#handleMessage (https://jsr.io/@lambdalisue/messagepack-rpc/2.4.0/session.ts:272:42)\n" +
"    at Object.write (https://jsr.io/@lambdalisue/messagepack-rpc/2.4.0/session.ts:165:63)",

@lambdalisue
Copy link
Member

If that stack trace is all you have, it only points to the error within Denops itself and does not include the essential information about the error location in the Denops plugin. Do you have an example where the Denops plugin itself is throwing an error?

@Shougo
Copy link
Contributor Author

Shougo commented Nov 25, 2024

For example this.

    async loadConfig(arg1: unknown): Promise<void> {
      await lock.lock(async () => {
        const path = ensure(arg1, is.String) as string;
        try {
          // NOTE: Import module with fragment so that reload works properly.
          // https://github.com/vim-denops/denops.vim/issues/227
          const mod = await import(
            `${toFileUrl(path).href}#${performance.now()}`
          );
          const obj = new mod.Config();
          await obj.config({ denops, contextBuilder, setAlias });
        } catch (e) {
          if (isDenoCacheIssueError(e)) {
            console.warn("*".repeat(80));
            console.warn(`Deno module cache issue is detected.`);
            console.warn(
              `Execute '!deno cache --reload "${path}"' and restart Vim/Neovim.`,
            );
            console.warn("*".repeat(80));
          }

          console.error(`Failed to load file '${path}': ${e}`);
          throw e;
        }
      });
      return Promise.resolve();
    },

@lambdalisue
Copy link
Member

I mean the error message difference itself.

@Shougo
Copy link
Contributor Author

Shougo commented Nov 26, 2024

For example this.

    async loadConfig(arg1: unknown): Promise<void> {
      await lock.lock(async () => {
        const path = ensure(arg1, is.String) as string;
        try {
          // NOTE: Import module with fragment so that reload works properly.
          // https://github.com/vim-denops/denops.vim/issues/227
          const mod = await import(
            `${toFileUrl(path).href}#${performance.now()}`
          );
          const obj = new mod.Config();
          await obj.config({ denops, contextBuilder, setAlias });
        } catch (e) {
          if (isDenoCacheIssueError(e)) {
            console.warn("*".repeat(80));
            console.warn(`Deno module cache issue is detected.`);
            console.warn(
              `Execute '!deno cache --reload "${path}"' and restart Vim/Neovim.`,
            );
            console.warn("*".repeat(80));
          }

          console.error(`Failed to load file '${path}': ${e}`);
          throw e;
        }
      });
      return Promise.resolve();
    },

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants