Skip to content

bug: Change error handling to prevent UI crash #1588

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

Merged
merged 12 commits into from
Jul 8, 2025
Merged

Conversation

LucasParraF
Copy link
Contributor

@LucasParraF LucasParraF commented Jun 13, 2025

Description

BHE and BHCE were crashing when an error on the GraphView component appeared. For BHCE, Explore view used this component and was affected by this bug. In order to fix this, I refactored the error handle on the component so it would render a new component with an error alert to keep consistency on how were managing other errors

Motivation and Context

Resolves https://specterops.atlassian.net/browse/BED-5948

How Has This Been Tested?

Created test for GraphView component

Screenshots (optional):

BHCE-Explore.mov

Types of changes

  • Bug fix (non-breaking change which fixes an issue)

Checklist:

  • [ x ] I have met the contributing prerequisites
  • [ x ] I have ensured that related documentation is up-to-date
    • Open API docs
    • Code comments (GoDocs / JSDocs)
  • [ x ] I have followed proper test practices
    • Added/updated tests to cover my changes
    • All new and existing tests passed

Summary by CodeRabbit

  • New Features

    • Introduced a user-friendly error alert in the graph view to notify users of unexpected errors and prompt them to refresh the page.
  • Bug Fixes

    • Improved error handling in the graph view to prevent unhandled exceptions and display a clear error message.
  • Tests

    • Added tests to ensure the graph view renders correctly and displays an error alert when a server error occurs.

Copy link
Contributor

coderabbitai bot commented Jun 13, 2025

Walkthrough

A new GraphViewErrorAlert React component is introduced to display a user-friendly error alert within the GraphView component when a server error occurs. The error handling logic in GraphView is updated to render this alert instead of throwing an exception. Corresponding tests are added to verify the new error UI and normal rendering behavior.

Changes

File(s) Change Summary
cmd/ui/src/views/Explore/GraphView.test.tsx Added tests for GraphView, including error handling and rendering behavior with mocked server responses.
cmd/ui/src/views/Explore/GraphView.tsx Updated to render GraphViewErrorAlert on error instead of throwing, altering error handling flow.
packages/javascript/bh-shared-ui/src/views/Explore/ExploreSearch/GraphViewErrorAlert.tsx Introduced new GraphViewErrorAlert component for displaying error alerts using Material-UI.
packages/javascript/bh-shared-ui/src/views/Explore/ExploreSearch/index.ts Exported GraphViewErrorAlert for public usage.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant GraphView
    participant Server
    participant GraphViewErrorAlert

    User->>GraphView: Render component
    GraphView->>Server: Fetch graph data
    Server-->>GraphView: Error response (e.g., 500)
    GraphView->>GraphViewErrorAlert: Render error alert
    GraphViewErrorAlert-->>User: Display error message
Loading

Suggested labels

bug, user interface

Poem

🐇
A hop, a leap, a gentle cheer,
Error alerts now appear!
No more crashes, just a sign,
"Please refresh"—you’ll be fine.
With tests to check and code anew,
The graph view’s safer—thanks to you!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 38f1463 and fe6af62.

📒 Files selected for processing (1)
  • cmd/ui/src/views/Explore/GraphView.test.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/ui/src/views/Explore/GraphView.test.tsx
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@LucasParraF LucasParraF changed the title Bed 5948 UI crash fix bug: Change error handling to prevent UI crash Jun 23, 2025
@LucasParraF
Copy link
Contributor Author

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jun 23, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@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: 4

🧹 Nitpick comments (1)
packages/javascript/bh-shared-ui/src/views/Explore/ExploreSearch/GraphViewErrorAlert.tsx (1)

25-25: Consider making the error message more informative.

The generic error message doesn't provide users with context about what went wrong. Consider making the component accept props to display more specific error information when available.

-const GraphViewErrorAlert = () => {
+interface GraphViewErrorAlertProps {
+    message?: string;
+}
+
+const GraphViewErrorAlert = ({ message }: GraphViewErrorAlertProps) => {
     const theme = useTheme();
     return (
         <Box display={'flex'} justifyContent={'center'} mt={theme.spacing(8)} mx={theme.spacing(4)}>
             <Alert severity={'error'}>
                 <AlertTitle>Error</AlertTitle>
-                <p>An unexpected error has occurred. Please refresh the page and try again.</p>
+                <p>{message || 'An unexpected error has occurred. Please refresh the page and try again.'}</p>
             </Alert>
         </Box>
     );
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3283784 and 38f1463.

📒 Files selected for processing (8)
  • cmd/ui/src/views/Explore/GraphView.test.tsx (1 hunks)
  • cmd/ui/src/views/Explore/GraphView.tsx (3 hunks)
  • packages/go/graphschema/ad/ad.go (0 hunks)
  • packages/go/graphschema/azure/azure.go (0 hunks)
  • packages/go/graphschema/common/common.go (0 hunks)
  • packages/go/graphschema/graph.go (0 hunks)
  • packages/javascript/bh-shared-ui/src/views/Explore/ExploreSearch/GraphViewErrorAlert.tsx (1 hunks)
  • packages/javascript/bh-shared-ui/src/views/Explore/ExploreSearch/index.ts (1 hunks)
💤 Files with no reviewable changes (4)
  • packages/go/graphschema/azure/azure.go
  • packages/go/graphschema/graph.go
  • packages/go/graphschema/common/common.go
  • packages/go/graphschema/ad/ad.go
🔇 Additional comments (4)
packages/javascript/bh-shared-ui/src/views/Explore/ExploreSearch/GraphViewErrorAlert.tsx (1)

19-29: Well-implemented error alert component.

The component correctly uses Material-UI components and theming for consistent styling. The centered layout and error severity are appropriate for this use case.

packages/javascript/bh-shared-ui/src/views/Explore/ExploreSearch/index.ts (1)

18-18: Export follows established patterns.

The export is correctly placed and follows the existing naming conventions in the index file.

cmd/ui/src/views/Explore/GraphView.tsx (2)

23-23: Import correctly added for new error alert component.

The import follows the existing pattern and is properly included with other bh-shared-ui imports.


120-120: Excellent fix for preventing UI crashes.

Replacing the error throw with component rendering is the correct approach. This prevents unhandled exceptions from crashing the UI while providing users with a clear error message and recovery instructions.

Comment on lines 22 to 26
const server = setupServer(
rest.get('/api/v2/graphs/cypher', (req, res, ctx) => {
return res(ctx.status(500));
})
);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add server lifecycle management.

The mock server is defined but not properly managed. You need to start and stop the server in your test lifecycle.

 const server = setupServer(
     rest.get('/api/v2/graphs/cypher', (req, res, ctx) => {
         return res(ctx.status(500));
     })
 );
+
+beforeAll(() => server.listen());
+afterEach(() => server.resetHandlers());
+afterAll(() => server.close());
📝 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 server = setupServer(
rest.get('/api/v2/graphs/cypher', (req, res, ctx) => {
return res(ctx.status(500));
})
);
const server = setupServer(
rest.get('/api/v2/graphs/cypher', (req, res, ctx) => {
return res(ctx.status(500));
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
🤖 Prompt for AI Agents
In cmd/ui/src/views/Explore/GraphView.test.tsx around lines 22 to 26, the mock
server is set up but lacks lifecycle management. Add server start and stop calls
by invoking server.listen() before tests run, server.resetHandlers() after each
test, and server.close() after all tests complete to properly manage the server
lifecycle and avoid side effects.

Comment on lines 33 to 41
it('displays an error message', async () => {
server.use;
render(<GraphView />);
const errorAlert = await waitFor(() =>
screen.findByText('An unexpected error has occurred. Please refresh the page and try again.')
);

expect(errorAlert).toBeInTheDocument;
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve test structure and assertions.

The test logic could be clearer and the server usage needs correction.

     it('displays an error message', async () => {
-        server.use;
         render(<GraphView />);
-        const errorAlert = await waitFor(() =>
-            screen.findByText('An unexpected error has occurred. Please refresh the page and try again.')
-        );
+        
+        const errorAlert = await screen.findByText(
+            'An unexpected error has occurred. Please refresh the page and try again.'
+        );
 
-        expect(errorAlert).toBeInTheDocument;
+        expect(errorAlert).toBeInTheDocument();
     });
📝 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
it('displays an error message', async () => {
server.use;
render(<GraphView />);
const errorAlert = await waitFor(() =>
screen.findByText('An unexpected error has occurred. Please refresh the page and try again.')
);
expect(errorAlert).toBeInTheDocument;
});
it('displays an error message', async () => {
render(<GraphView />);
const errorAlert = await screen.findByText(
'An unexpected error has occurred. Please refresh the page and try again.'
);
expect(errorAlert).toBeInTheDocument();
});
🤖 Prompt for AI Agents
In cmd/ui/src/views/Explore/GraphView.test.tsx around lines 33 to 41, the test
incorrectly calls server.use without invoking it and uses toBeInTheDocument
without parentheses. Fix this by properly calling server.use with the required
handler and change expect(errorAlert).toBeInTheDocument to
expect(errorAlert).toBeInTheDocument() to correctly assert the presence of the
error message.

@LucasParraF LucasParraF marked this pull request as ready for review June 26, 2025 19:17
Comment on lines 36 to 37
beforeEach(() => server.listen());
afterAll(() => server.close());
Copy link
Contributor

Choose a reason for hiding this comment

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

These typically go outside of the describe block. We should remove these lines and add the ones that coderabbit posted in the comment right above and outside of the describe block like this:

 const server = setupServer(
     rest.get('/api/v2/graphs/cypher', (req, res, ctx) => {
         return res(ctx.status(500));
     })
 );

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

describe('GraphView', () => {
...

Copy link
Contributor

@urangel urangel left a comment

Choose a reason for hiding this comment

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

A little cleanup requested in the test but looks good otherwise!

@LucasParraF LucasParraF merged commit 204b34c into main Jul 8, 2025
9 checks passed
@LucasParraF LucasParraF deleted the BED-5948-UI-crash-fix branch July 8, 2025 20:00
@github-actions github-actions bot locked and limited conversation to collaborators Jul 8, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants