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

fix: simplified error messages for user at profile settings #2467

Closed

Conversation

bandhan-majumder
Copy link
Contributor

@bandhan-majumder bandhan-majumder commented Nov 24, 2024

What kind of change does this PR introduce?

A bug fix.

Issue Number:

Fixes #2464

Snapshots/Videos:

https://www.loom.com/share/0bad7f7199a14fa6b4e3d085231d5127?sid=753e38b4-e287-435b-89af-e1f8048225e0

Summary

While updating user profile at Talawa User Portal, user used not to get user friendly errors. I have simplified the error which will come one by one in a user friendly readable manner helping user to understand the fields they are missing/giving wrong data into. I have also added translation of errors.

Other information

While testing the fields, I found out that the separated option at Marital Status was also giving error if selected because of spelling error in enums. Fixed that too.

Have you read the contributing guide?

yes

Summary by CodeRabbit

  • New Features
    • Introduced new error messages for input validation across multiple languages, enhancing user guidance.
      • English: Valid phone number, education grade, employment status, marital status prompts.
      • French, Hindi, Spanish, and Chinese: Corresponding prompts added for each language.
  • Bug Fixes
    • Corrected spelling of "SEPERATED" to "SEPARATED" in the marital status enumeration.
  • Improvements
    • Enhanced error handling to provide more specific feedback based on various input errors.

Copy link
Contributor

coderabbitai bot commented Nov 24, 2024

Walkthrough

This pull request introduces new error messages for input validation in multiple localization files, including English, French, Hindi, Spanish, and Chinese. Each locale receives specific messages to guide users on valid inputs for phone numbers, education grades, employment statuses, and marital statuses. Additionally, a correction is made to the spelling of "SEPERATED" in the GraphQL schema. The errorHandler function is also modified to improve error handling by allowing for more flexible and specific error message evaluations.

Changes

File Change Summary
public/locales/en/errors.json Added new error messages for phone number, education grade, employment status, and marital status; minor formatting adjustment to "errorLoading".
public/locales/fr/errors.json Added new error messages for phone number, education grade, employment status, and marital status; minor formatting adjustment to "errorLoading".
public/locales/hi/errors.json Added new error messages for phone number, education grade, employment status, and marital status; no change to "errorLoading".
public/locales/sp/errors.json Added new error messages for phone number, education grade, employment status, and marital status; minor formatting adjustment to "errorLoading".
public/locales/zh/errors.json Added new error messages for phone number, education grade, employment status, and marital status; no change to "errorLoading".
schema.graphql Corrected spelling of "SEPERATED" to "SEPARATED" in MaritalStatus enum.
src/utils/errorHandler.tsx Enhanced errorHandler function for improved error message handling, allowing for more specific feedback based on error content.

Assessment against linked issues

Objective Addressed Explanation
Error messages should be user-friendly for invalid inputs (e.g., phone number, education grade) (#2464)
Simplify error messages to guide users on required fields (#2464)

Possibly related PRs

  • [Translation] Fix post id bug and side translations #2074: The changes in this PR involve localization updates similar to the main PR, which also focuses on enhancing error messages in localization files. Both PRs add new entries related to user input validation in their respective localization files.

Poem

🐇 In the forest of code, where errors once bloomed,
New messages sprout, dispelling the gloom.
"Please enter a number," they cheerfully say,
Guiding the users, lighting their way.
With each little change, our portal's aglow,
A friendlier place for all who will show! 🌼


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.

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

Our Pull Request Approval Process

We have these basic policies to make the approval process smoother for our volunteer team.

Testing Your Code

Please make sure your code passes all tests. Our test code coverage system will fail if these conditions occur:

  1. The overall code coverage drops below the target threshold of the repository
  2. Any file in the pull request has code coverage levels below the repository threshold
  3. Merge conflicts

The process helps maintain the overall reliability of the code base and is a prerequisite for getting your PR approved. Assigned reviewers regularly review the PR queue and tend to focus on PRs that are passing.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Congratulations on making your first PR! 🎊 If you haven't already, check out our Contributing Guidelines and PR Reporting Guidelines to ensure that you are following our guidelines for contributing and creating PR.

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: 1

🧹 Outside diff range and nitpick comments (6)
public/locales/zh/errors.json (1)

11-11: Consider revising the phone number validation message.

The current message "请选择一个有效的电话号码" (Please select a valid phone number) implies that the user needs to select from options. Since phone numbers are typically entered rather than selected, consider changing to "请输入一个有效的电话号码" (Please enter a valid phone number).

-  "invalidPhoneNumber": "请选择一个有效的电话号码",
+  "invalidPhoneNumber": "请输入一个有效的电话号码",
public/locales/hi/errors.json (1)

11-14: LGTM! Consider minor improvement to phone number message

The error messages are clear, polite, and user-friendly. Consider removing the hyphen from "फोन-नंबर" to make it "फोन नंबर" for more natural Hindi text.

-  "invalidPhoneNumber": "कृपया एक मान्य फोन-नंबर दर्ज करे",
+  "invalidPhoneNumber": "कृपया एक मान्य फोन नंबर दर्ज करे",
public/locales/fr/errors.json (1)

10-10: Add trailing period for consistency

Other error messages in the file end with periods. Consider adding a period at the end of this message for consistency.

-  "errorLoading": "Une erreur s'est produite lors du chargement des données {{entity}}",
+  "errorLoading": "Une erreur s'est produite lors du chargement des données {{entity}}.",
public/locales/en/errors.json (1)

10-10: Fix spelling error in error message

The word "occurred" is misspelled as "occured" in the error message.

-  "errorLoading": "Error occured while loading {{entity}} data",
+  "errorLoading": "Error occurred while loading {{entity}} data",
src/utils/errorHandler.tsx (2)

13-14: Consider using error codes or types for more robust error handling.

The current implementation relies on string matching of error messages, which can be fragile if the API messages change. Consider refactoring to use error codes or custom error types for more maintainable error handling.

Example approach:

interface TalawaError extends Error {
  code: string;
  field?: string;
}

// Usage in switch statement
switch (error.code) {
  case 'INVALID_PHONE':
    toast.error(tErrors('invalidPhoneNumber'));
    break;
  // ...
}

Add test coverage for new error validation cases

The current test file only covers three scenarios:

  • "Failed to fetch" error
  • Generic error message
  • Null error object

Missing test coverage for the newly added validation cases:

  • Invalid phone number
  • Invalid education grade
  • Invalid employment status
  • Invalid marital status
🔗 Analysis chain

Line range hint 1-35: Add unit tests for new error cases.

The error handler has been significantly modified with new cases, but there's no indication of corresponding test updates. Please ensure all new error cases are covered by unit tests.

Would you like me to help generate test cases for the new error scenarios?


Let me check the content of the test files to verify the test coverage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for related test files and their content
fd -e test.tsx -e spec.tsx errorHandler
rg -l "errorHandler.*test|test.*errorHandler"

Length of output: 151


Script:

#!/bin/bash
# Check content of errorHandler.test.tsx
cat src/utils/errorHandler.test.tsx

Length of output: 1246

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 084ac7e and 570cfb8.

📒 Files selected for processing (7)
  • public/locales/en/errors.json (1 hunks)
  • public/locales/fr/errors.json (1 hunks)
  • public/locales/hi/errors.json (1 hunks)
  • public/locales/sp/errors.json (1 hunks)
  • public/locales/zh/errors.json (1 hunks)
  • schema.graphql (2 hunks)
  • src/utils/errorHandler.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • schema.graphql
🔇 Additional comments (8)
public/locales/zh/errors.json (1)

11-14: LGTM! Clear and consistent error messages.

The new validation messages are well-structured, user-friendly, and maintain consistency with the existing messages in the file. They align perfectly with the PR objective of simplifying error messages for users.

public/locales/hi/errors.json (1)

11-14: Verify translation consistency across the application

Let's ensure these new translations are consistent with existing Hindi text in the application.

public/locales/fr/errors.json (2)

11-14: Well-structured validation messages

The new validation messages are excellent:

  • Clear and user-friendly
  • Consistent structure using "Veuillez" (Please)
  • Accurate French translations
  • Each message addresses a single validation issue

This implementation aligns perfectly with the PR's objective of providing simplified, user-friendly error messages.


11-14: Verify consistency across all language files

Let's ensure these new validation messages are consistently implemented across all language files.

✅ Verification successful

All validation messages are consistently present across language files

The verification confirms that all four validation messages (invalidPhoneNumber, invalidEducationGrade, invalidEmploymentStatus, invalidMaritalStatus) are properly implemented across all language files (English, French, Spanish, Chinese, and Hindi). Each message maintains consistent meaning and structure across translations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if all language files contain the new validation messages
# and follow the same structure

# Find all locale files
echo "Checking validation messages across all language files:"
for key in invalidPhoneNumber invalidEducationGrade invalidEmploymentStatus invalidMaritalStatus; do
  echo "\nChecking '$key' translations:"
  fd "errors.json" public/locales --exec jq -r --arg key "$key" '.[$key] // "*** MISSING ***"' {}
done

Length of output: 2112

public/locales/en/errors.json (1)

11-14: LGTM! Clear and consistent validation messages

The new error messages are well-structured, user-friendly, and follow a consistent pattern. They align perfectly with the PR's objective of providing clearer error messages.

Let's verify that translations exist for these new messages:

✅ Verification successful

All translations are present across all locales

The verification confirms that all new validation messages (invalidPhoneNumber, invalidEducationGrade, invalidEmploymentStatus, invalidMaritalStatus) exist in all locale files (en, fr, hi, sp, zh) across common, errors, and translation files. The translations are properly maintained across the internationalization system.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if translations exist for all new error messages in other locale files

# Define the keys to check
KEYS=("invalidPhoneNumber" "invalidEducationGrade" "invalidEmploymentStatus" "invalidMaritalStatus")

# Find all locale files
echo "Checking locale files for translations..."
for locale_file in $(fd -e json . public/locales); do
  echo "\nChecking $locale_file"
  for key in "${KEYS[@]}"; do
    if jq "has(\"$key\")" "$locale_file" > /dev/null; then
      echo "$key exists"
    else
      echo "✗ Missing translation for $key"
    fi
  done
done

Length of output: 12211

public/locales/sp/errors.json (2)

10-10: LGTM! Message format and translation are correct.

The error message maintains proper Spanish grammar and consistent placeholder usage.


11-14: Well-structured validation messages that align with PR objectives!

The new error messages are clear, user-friendly, and properly translated to Spanish. They effectively fulfill the PR's goal of simplifying error messages for users.

Let's verify consistency across other locale files:

✅ Verification successful

Validation messages are consistent across all locale files

All the new validation messages (invalidPhoneNumber, invalidEducationGrade, invalidEmploymentStatus, invalidMaritalStatus) are properly translated and present in all locale files (en, fr, hi, zh, sp). Each translation:

  • Maintains consistent meaning across languages
  • Uses appropriate language-specific grammar and formatting
  • Follows a polite, user-friendly tone
  • Conveys the same validation requirements
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if all locale files have the same validation messages
# Expected: All locale files should have these new keys with appropriate translations

for key in "invalidPhoneNumber" "invalidEducationGrade" "invalidEmploymentStatus" "invalidMaritalStatus"; do
  echo "Checking translations for: $key"
  for locale in en fr hi zh sp; do
    echo "=== $locale ==="
    jq ".[\"$key\"]" "public/locales/$locale/errors.json"
  done
done

Length of output: 4099

src/utils/errorHandler.tsx (1)

15-28: 🛠️ Refactor suggestion

Improve error message matching specificity.

The current string matching using includes() might catch partial matches unintentionally. Consider using more specific error message patterns or regular expressions.

Example improvement:

-case errorMessage.includes('does not exist in "EducationGrade"'):
+case /^Value ".*" does not exist in "EducationGrade"/.test(errorMessage):

Also, verify that these error messages exactly match what the API returns:

src/utils/errorHandler.tsx Outdated Show resolved Hide resolved
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: 0

🧹 Outside diff range and nitpick comments (2)
src/utils/errorHandler.tsx (2)

14-14: Consider using a more maintainable error handling structure.

While switch(true) works, it can become harder to maintain as more error cases are added. Consider refactoring to use specific error types or error codes for better maintainability.

Example approach using error types:

type ValidationError = {
  code: 'PHONE' | 'EDUCATION' | 'EMPLOYMENT' | 'MARITAL' | 'NETWORK';
  message: string;
};

// Then handle errors based on their code instead of string matching
switch (error.code) {
  case 'PHONE':
    toast.error(tErrors('invalidPhoneNumber'));
    break;
  // ...
}

31-32: Enhance error logging for better debugging.

While showing a generic error to users is good, the current console logging could be more informative for debugging purposes.

-console.log(errorMessage);
+console.error('Error in API request:', {
+  message: errorMessage,
+  timestamp: new Date().toISOString(),
+  // Add any relevant context from 'a' parameter if needed
+});
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 570cfb8 and 173a656.

📒 Files selected for processing (6)
  • public/locales/en/errors.json (1 hunks)
  • public/locales/fr/errors.json (1 hunks)
  • public/locales/hi/errors.json (1 hunks)
  • public/locales/sp/errors.json (1 hunks)
  • public/locales/zh/errors.json (1 hunks)
  • src/utils/errorHandler.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • public/locales/en/errors.json
  • public/locales/fr/errors.json
  • public/locales/hi/errors.json
  • public/locales/zh/errors.json
🔇 Additional comments (5)
public/locales/sp/errors.json (2)

10-10: LGTM! Error loading message is well-formatted

The Spanish translation is grammatically correct and maintains consistent placeholder usage.


11-15: Translations look good with minor formatting suggestions

The new error messages are clear, concise, and properly translated to Spanish. They align well with the PR objective of providing user-friendly error messages.

Minor suggestion: Consider adding a comma after "Por favor" in all messages for consistency:

-  "invalidEducationGrade": "Por favor seleccione un grado de educación válido",
+  "invalidEducationGrade": "Por favor, seleccione un grado de educación válido",
-  "invalidEmploymentStatus": "Por favor seleccione un estado de empleo válido",
+  "invalidEmploymentStatus": "Por favor, seleccione un estado de empleo válido",
-  "invalidMaritalStatus": "Por favor seleccione un estado civil válido",
+  "invalidMaritalStatus": "Por favor, seleccione un estado civil válido"

Let's verify the consistency of these messages across other locale files:

✅ Verification successful

Translations are consistent across all locale files with minor formatting variations

The error messages are properly translated and maintain consistent meaning across all supported languages (English, Spanish, French, Hindi, and Chinese). Each translation:

  • Preserves the core validation message
  • Uses appropriate language-specific politeness markers ("Please", "Por favor", "Veuillez", "कृपया", "请")
  • Maintains consistent structure within each language

The original suggestion about adding commas after "Por favor" in Spanish is stylistic and can be left to the team's localization guidelines, as other languages follow their own punctuation conventions correctly.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistency of new error messages across all locale files

# Find all error.json files and check their content
fd 'errors.json' public/locales -x cat {} \; | grep -A 1 -B 1 'invalidPhoneNumber\|invalidEducationGrade\|invalidEmploymentStatus\|invalidMaritalStatus\|defaultError'

Length of output: 2123

src/utils/errorHandler.tsx (3)

13-13: LGTM! Good practice for error handling.

Extracting the error message into a variable improves code readability and prevents multiple property accesses.


15-28: Successfully implements user-friendly error messages.

The implementation aligns well with the PR objectives by providing specific, translated error messages for each validation case.


18-28: Verify translation keys exist for all error messages.

Let's ensure all translation keys used in the error handler exist across all locale files.

✅ Verification successful

All translation keys are present across all locale files

The verification confirms that all required error message translation keys (invalidPhoneNumber, invalidEducationGrade, invalidEmploymentStatus, and invalidMaritalStatus) exist in all locale files (en, fr, hi, sp, and zh). Each key returned true for all locale files, indicating proper internationalization coverage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all required translation keys exist in all locale files

# Required keys from the error handler
REQUIRED_KEYS=("invalidPhoneNumber" "invalidEducationGrade" "invalidEmploymentStatus" "invalidMaritalStatus")

# Find all locale files
fd 'errors.json' public/locales

# Check each key in each locale file
for key in "${REQUIRED_KEYS[@]}"; do
  echo "Checking key: $key"
  fd 'errors.json' public/locales -x jq "has(\"$key\")"
done

Length of output: 1127

@palisadoes
Copy link
Contributor

  1. This needs to be closed. We are working on the develop-postrgres branch.
  2. Next time, ask to be assigned the issue before submitting a PR.

@palisadoes palisadoes closed this Nov 25, 2024
@bandhan-majumder
Copy link
Contributor Author

Sorry for that. I am solving the error in develop-postgres branch now, it's not that much of unreadable, but can be improved as it only sends one message in every error.

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