Skip to content

fix: improve error handling in avatar upload components#37908

Open
adityasuhane-06 wants to merge 2 commits into
RocketChat:developfrom
adityasuhane-06:fix/avatar-upload-error-handling-improved
Open

fix: improve error handling in avatar upload components#37908
adityasuhane-06 wants to merge 2 commits into
RocketChat:developfrom
adityasuhane-06:fix/avatar-upload-error-handling-improved

Conversation

@adityasuhane-06
Copy link
Copy Markdown

@adityasuhane-06 adityasuhane-06 commented Dec 20, 2025

Description

This PR improves error handling in avatar upload components by refactoring to use a shared utility function and providing more specific error messages to users.

Changes

  • RoomAvatarEditor.tsx: Refactored to use readFileAsDataURL utility instead of inline FileReader logic
  • UserAvatarEditor.tsx: Enhanced error handling to distinguish between file read failures and format validation errors

Error Scenarios Handled

  1. File Read Failures: Shows "File Upload Error" toast when FileReader fails (corrupted files, permission issues)
  2. Invalid Format: Shows "Invalid Format. Only image type is allowed" toast when image format validation fails

Benefits

  • Code Consistency: Both components now use the same file reading mechanism
  • Better UX: Users receive specific error messages instead of silent failures
  • Maintainability: Reduced code duplication by using shared utility function
  • Cleaner Code: Try/catch pattern is simpler than manual FileReader event handlers

How to Test

User Profile - Invalid Format:

  1. Go to your profile page
  2. Click upload avatar button
  3. Select a .txt file or non-image file
  4. Expected: Toast message "Invalid Format. Only image type is allowed"

Room Info - File Read Error:

  1. Open a room
  2. Go to room info/settings
  3. Attempt to upload an avatar
  4. Expected: Proper error handling with toast message

Valid Upload:

  1. Upload a valid PNG/JPG image in either location
  2. Expected: Avatar updates successfully with no errors

Related Issues

Fixes #37895

Summary by CodeRabbit

  • Bug Fixes

    • Avatar uploads now show distinct, user-friendly toasts for invalid image formats (Avatar_format_invalid) versus upload failures (FileUpload_Error), clarifying issues for users.
    • Prevents invalid images from being applied as previews.
  • Refactor

    • Streamlined avatar image processing to a promise-based flow for more reliable and maintainable uploads.

✏️ Tip: You can customize this high-level summary in your review settings.

@adityasuhane-06 adityasuhane-06 requested a review from a team as a code owner December 20, 2025 12:11
@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Dec 20, 2025

⚠️ No Changeset found

Latest commit: c89a5fb

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Dec 20, 2025

Walkthrough

RoomAvatarEditor and UserAvatarEditor now use the shared readFileAsDataURL helper and surface file-read and format-validation failures via explicit error toasts (FileUpload_Error, Avatar_format_invalid) instead of failing silently.

Changes

Cohort / File(s) Summary
Avatar upload components
apps/meteor/client/components/avatar/RoomAvatarEditor.tsx, apps/meteor/client/components/avatar/UserAvatarEditor/UserAvatarEditor.tsx
Replaced manual FileReader flows with the readFileAsDataURL helper; added try/catch around file reading; show FileUpload_Error on read exceptions and Avatar_format_invalid when image format validation fails; adjusted control flow to call setAvatarObj only after successful validation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Verify readFileAsDataURL integration and that its errors propagate to the catch block.
  • Confirm Avatar_format_invalid is dispatched for invalid formats in both components.
  • Confirm FileUpload_Error is dispatched when file reading fails.
  • Test with corrupted files, non-image files, and valid images to ensure toasts and preview/upload flows behave as expected.

Poem

🐇 I nibble bytes and tidy the fray,
Read files with care so no errors stay.
If formats balk or readers sigh, I sing—
Toasts lift like carrots on a caring wing. 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: improve error handling in avatar upload components' accurately reflects the main objective of the PR to enhance error handling in avatar upload components.
Linked Issues check ✅ Passed The PR addresses all coding objectives from issue #37895: adds FileReader error handling in RoomAvatarEditor, adds format validation error messaging in UserAvatarEditor, standardizes both components using readFileAsDataURL utility, and implements clear toast messages for both error scenarios.
Out of Scope Changes check ✅ Passed All changes directly address the objectives outlined in issue #37895 with no extraneous modifications detected in the file summaries.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4952000 and c89a5fb.

📒 Files selected for processing (1)
  • apps/meteor/client/components/avatar/UserAvatarEditor/UserAvatarEditor.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/meteor/client/components/avatar/UserAvatarEditor/UserAvatarEditor.tsx

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/meteor/client/components/avatar/UserAvatarEditor/UserAvatarEditor.tsx (1)

33-49: Good improvement in error handling, but consider order of operations.

The distinction between Avatar_format_invalid and FileUpload_Error correctly separates format validation from file read failures.

However, setAvatarObj(avatarObj) at line 35 is called before format validation completes. If isValidImageFormat returns false, the parent component still holds the invalid file reference while the user sees an error toast—this could lead to confusing state if the user later submits the form.

Consider moving setAvatarObj(avatarObj) inside the if block (after line 39) so the avatar object is only set when format validation passes.

🔎 Suggested fix
 const setUploadedPreview = useCallback(
   async (file: File, avatarObj: AvatarObject) => {
-    setAvatarObj(avatarObj);
     try {
       const dataURL = await readFileAsDataURL(file);

       if (await isValidImageFormat(dataURL)) {
+        setAvatarObj(avatarObj);
         setNewAvatarSource(dataURL);
       } else {
         dispatchToastMessage({ type: 'error', message: t('Avatar_format_invalid') });
       }
     } catch (error) {
       dispatchToastMessage({ type: 'error', message: t('FileUpload_Error') });
     }
   },
   [setAvatarObj, t, dispatchToastMessage],
 );
🧹 Nitpick comments (1)
apps/meteor/client/components/avatar/RoomAvatarEditor.tsx (1)

13-13: Consider relocating shared utility.

readFileAsDataURL is now used by both UserAvatarEditor and RoomAvatarEditor, but resides inside the UserAvatarEditor folder. For discoverability and to reflect its shared nature, consider moving it to a common location such as ../../lib/utils/ alongside isValidImageFormat.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9657d38 and af06cc8.

📒 Files selected for processing (2)
  • apps/meteor/client/components/avatar/RoomAvatarEditor.tsx (2 hunks)
  • apps/meteor/client/components/avatar/UserAvatarEditor/UserAvatarEditor.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • apps/meteor/client/components/avatar/UserAvatarEditor/UserAvatarEditor.tsx
  • apps/meteor/client/components/avatar/RoomAvatarEditor.tsx
🧠 Learnings (1)
📓 Common learnings
Learnt from: aleksandernsilva
Repo: RocketChat/Rocket.Chat PR: 36974
File: apps/meteor/client/components/Omnichannel/OutboundMessage/components/OutboundMessageWizard/forms/MessageForm/MessageForm.tsx:124-129
Timestamp: 2025-09-18T17:32:33.969Z
Learning: The ARIA mismatch issue in MessageForm's template field (where FieldError id used templateId instead of messageFormId) was addressed in PR #36972 through refactoring the template field into a separate TemplateField component, which uses consistent templateFieldId for both aria-describedby and FieldError id.
🔇 Additional comments (1)
apps/meteor/client/components/avatar/RoomAvatarEditor.tsx (1)

28-40: Clean refactor with proper error handling.

The implementation correctly:

  • Uses the shared readFileAsDataURL utility for consistency
  • Validates format before calling onChangeAvatar, ensuring only valid images update state
  • Distinguishes between file read errors and format validation errors with appropriate toast messages

- Refactored RoomAvatarEditor to use readFileAsDataURL utility for consistency
- Added explicit error handling for both file read and format validation failures
- Distinguished between FileUpload_Error (read failures) and Avatar_format_invalid (format issues)
- Improved code maintainability by using shared utility function

Fixes RocketChat#37895
@adityasuhane-06 adityasuhane-06 force-pushed the fix/avatar-upload-error-handling-improved branch from af06cc8 to 4952000 Compare December 20, 2025 12:27
- Move setAvatarObj call inside validation check
- Ensures avatar object is only updated for valid images
- Addresses CodeRabbit review suggestion
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.

Missing Error Handling in Avatar Upload Components

1 participant