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 invalid inputs at profile settings #2473

Conversation

bandhan-majumder
Copy link
Contributor

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

What kind of change does this PR introduce?

A bugfix.

Issue Number:

Fixes #2464

Snapshots/Videos:

https://www.loom.com/share/0a0e7d6b5b754bbfb8e9b6b8bd6e6161?sid=074df4c5-6119-43f7-827d-6108f36f6cee

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

Added a 400 handler too.

Have you read the contributing guide?

Yes

Summary by CodeRabbit

  • New Features

    • Introduced new error messages for better user feedback on validation issues, including phone numbers, education grades, employment statuses, and marital statuses.
    • Added general error messages for server response issues and generic errors across multiple languages (English, French, Hindi, Spanish, Chinese).
  • Bug Fixes

    • Improved error handling logic to provide more specific feedback based on different error scenarios.
  • Documentation

    • Enhanced localization for error messages to improve clarity for users in various languages.

Copy link
Contributor

coderabbitai bot commented Nov 25, 2024

Walkthrough

The changes in this pull request involve the addition of new error messages across multiple localization files (errors.json) for English, French, Hindi, Spanish, and Chinese. These messages provide specific feedback for various user input validation scenarios and server response issues. Additionally, the errorHandler function has been modified to improve error handling by utilizing a streamlined approach for managing error messages and improving user notifications.

Changes

File Change Summary
public/locales/en/errors.json Added new error messages for phone number, education grade, employment status, marital status, error 400, and a default error. Reformatted existing "errorLoading" message.
public/locales/fr/errors.json Added new error messages for phone number, education grade, employment status, marital status, error 400, and a default error. "errorLoading" message remains unchanged.
public/locales/hi/errors.json Added new error messages for phone number, education grade, employment status, marital status, error 400, and a default error. "errorLoading" message remains unchanged.
public/locales/sp/errors.json Added new error messages for phone number, education grade, employment status, marital status, error 400, and a default error. "errorLoading" message remains unchanged.
public/locales/zh/errors.json Added new error messages for phone number, education grade, employment status, marital status, error 400, and a default error. "errorLoading" message remains unchanged.
src/utils/errorHandler.tsx Modified the errorHandler function to streamline error message handling and improve user notifications.

Assessment against linked issues

Objective Addressed Explanation
Error messages should be user-friendly and specific for invalid inputs. (#2464)
Enhance error handling to provide clearer feedback to users. (#2464)

Possibly related PRs

  • [Translations] Errors and Success #2078: This PR adds new error messages to the errors.json file, including messages for invalid inputs such as "invalidPhoneNumber," "invalidEducationGrade," "invalidEmploymentStatus," and "invalidMaritalStatus," which directly relates to the changes made in the main PR that also introduces similar error messages in the English locale.

Poem

🐇 In the land of code, where errors dwell,
New messages sprout, like a magic spell.
"Please try again," the rabbit does say,
With clearer guidance, we'll find our way!
So hop along, dear users, with glee,
For error handling's now as sweet as can be! 🌟


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

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

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

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

11-14: Enhance validation messages for better user guidance

While the translations are grammatically correct, they could be more user-friendly and specific. Consider these improvements:

-  "invalidPhoneNumber": "请选择一个有效的电话号码",
+  "invalidPhoneNumber": "请输入正确的电话号码格式",
-  "invalidEducationGrade": "请选择教育年级",
+  "invalidEducationGrade": "请从列表中选择您的教育程度",
-  "invalidEmploymentStatus": "请选择有效的就业状况",
+  "invalidEmploymentStatus": "请从列表中选择您的就业状况",
-  "invalidMaritalStatus": "请选择有效的婚姻状况",
+  "invalidMaritalStatus": "请从列表中选择您的婚姻状况"

Rationale for changes:

  • Phone number: More specific about format requirement
  • Other fields: Clarify that options are available in a list
  • Added respectful form of address (您) which is more appropriate for user interfaces in Chinese

15-16: Consider improving technical error messages

The HTTP 400 error message is too technical for end users. Consider a more user-friendly approach:

-  "error400": "响应不成功. 从服务器收到状态代码 400",
+  "error400": "请求无法完成,请检查您的输入是否正确",

The default error message is well translated and appropriate for general use.


Translation inconsistencies found across locale files

Several inconsistencies in messaging structure and completeness were identified:

  • Spanish (sp) locale has untranslated entries: The first 7 entries are still in English
  • French (fr) and Hindi (hi) locales have incomplete messages: notFoundMsg and notAuthorised are truncated compared to English
  • Chinese (zh) locale has shorter error messages that may not convey the same level of detail (e.g., talawaApiUnavailable doesn't mention checking network connectivity)
  • The placeholder usage ({{msg}}, {{entity}}) is consistent across all locales, which is good
🔗 Analysis chain

Line range hint 1-16: Verify translations across all locale files

To ensure consistency across all locales, we should verify that the messaging structure and tone are uniform.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Compare structure of all locale files and check for missing translations

# List all locale files and their content
for locale in en fr hi sp zh; do
  echo "=== Checking $locale locale ==="
  if [ -f "public/locales/$locale/errors.json" ]; then
    # Check if all keys exist and print their values
    jq -r '. | to_entries | .[] | "\(.key): \(.value)"' "public/locales/$locale/errors.json"
  fi
done

Length of output: 4966

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

15-15: Consider simplifying the technical error message

The current message "error400": "Réponse non réussie. Code d'état 400 reçu du serveur" is too technical for end users.

Consider a more user-friendly version:

-  "error400": "Réponse non réussie. Code d'état 400 reçu du serveur",
+  "error400": "Désolé, votre requête n'a pas pu être traitée. Veuillez réessayer.",
public/locales/en/errors.json (1)

10-10: Fix typo in error message

The word "occured" is misspelled. It should be "occurred".

-  "errorLoading": "Error occured while loading {{entity}} data",
+  "errorLoading": "Error occurred while loading {{entity}} data",
public/locales/sp/errors.json (1)

11-14: LGTM! Translations are clear and consistent.

The Spanish translations are grammatically correct and maintain a consistent, polite tone using "por favor" for validation messages.

Consider renaming the directory from sp to es as it's the standard ISO language code for Spanish.

src/utils/errorHandler.tsx (1)

Line range hint 1-40: Consider implementing a centralized error handling system.

While the current changes improve error message clarity, consider implementing a more robust error handling system:

  1. Define an error registry with error codes and corresponding messages
  2. Implement error hierarchies for different types of validation errors
  3. Add error context/metadata support for better debugging
  4. Use proper logging infrastructure
  5. Consider implementing error boundaries for React components

This would make the system more maintainable and provide better error tracking capabilities.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6ae40a3 and 5e96c35.

📒 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)
🔇 Additional comments (11)
public/locales/zh/errors.json (1)

10-10: LGTM: Consistent formatting of existing message

The reformatted message maintains proper Chinese grammar and clarity.

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

11-14: Well-structured validation messages!

The validation messages are clear, consistent, and user-friendly. They follow good practices by:

  • Starting with "कृपया" (please) to maintain politeness
  • Clearly indicating the specific action required
  • Using consistent language structure across all validation messages

16-16: LGTM! Good fallback message

The default error message is well-crafted:

  • Acknowledges the error without technical details
  • Provides clear next steps for the user
  • Uses appropriate and friendly language

11-16: Verify translations across all locale files

Let's ensure these new error messages are consistently implemented across all supported languages.

✅ Verification successful

Let me generate another script to get more detailed information about the actual content of these files.

This will help us see if the translations exist but with different keys, or if they're missing entirely.


All error messages are properly translated across all locale files

The verification shows that all the new error messages (invalidPhoneNumber, invalidEducationGrade, invalidEmploymentStatus, invalidMaritalStatus, error400, and defaultError) are present and properly translated in all supported languages (en, fr, hi, sp, and zh).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if all new error keys exist in other locale files
# Expected: All locale files should have the same error keys

# Define the new keys to check
keys=("invalidPhoneNumber" "invalidEducationGrade" "invalidEmploymentStatus" "invalidMaritalStatus" "error400" "defaultError")

# Find all locale files
echo "Checking locale files for consistency..."
for locale_file in $(fd "errors.json" public/locales); do
  echo "\nChecking $locale_file"
  for key in "${keys[@]}"; do
    if ! grep -q "\"$key\":" "$locale_file"; then
      echo "❌ Missing key: $key"
    fi
  done
done

Length of output: 3657


Script:

#!/bin/bash
# Get the actual content of all error.json files to compare translations
for locale_file in $(fd "errors.json" public/locales); do
  echo -e "\n=== Content of $locale_file ===\n"
  cat "$locale_file"
done

Length of output: 5474

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

10-16: LGTM: Consistent JSON formatting

The new entries maintain consistent formatting with the existing messages and follow proper JSON structure.


11-14: Verify coverage of all profile field validations

The new validation messages cover phone, education, employment, and marital status. Let's ensure we haven't missed any other profile fields that require validation messages.

✅ Verification successful

Let me gather more information about the profile fields and their validations.


Let me search for profile-related components and forms to verify all validation fields.


Let me search for profile-related form fields and validation schemas in the codebase.


Based on the analysis of the codebase and locale files, I can now provide a final response regarding the validation messages coverage.

All required profile field validations are properly covered

The validation messages in errors.json cover all the essential profile fields that require validation:

  • Phone number validation: "invalidPhoneNumber"
  • Education grade validation: "invalidEducationGrade"
  • Employment status validation: "invalidEmploymentStatus"
  • Marital status validation: "invalidMaritalStatus"

This aligns with the profile fields found in the codebase:

  • Phone number input field
  • Education grade selection
  • Employment status selection
  • Marital status selection

The validation messages are also properly translated across different locale files (en, fr, hi, etc.) ensuring consistent user feedback across languages.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for form field validations in profile components
rg -t tsx -t ts "validation|required|invalid" src/ | grep -i "profile"

# Check other locale files for additional validation messages
fd -e json . public/locales | xargs rg "invalid.*Status|invalid.*Field"

Length of output: 1126


Script:

#!/bin/bash
# Search for profile-related form fields and validations
ast-grep --pattern 'const $_ = useForm<$_>({
  $$$
})'

# Search for profile-related validation schemas
rg "schema|validation" -A 5 -B 5

# Search for all error messages in English locale to compare
cat public/locales/en/errors.json

Length of output: 29227


Script:

#!/bin/bash
# Search for profile-related components and forms
fd -e tsx -e ts . src/ | grep -i "profile" | xargs cat

# Search for form field validations in any components
ast-grep --pattern 'const $_ = yup.object().shape({
  $$$
})'

# Search for validation schema definitions
rg "yup.string\(\)|yup.number\(\)" -A 2 -B 2

Length of output: 65355


Script:

#!/bin/bash
# Search for profile form fields and validation
rg -t tsx -t ts "Form\." -A 3 -B 3 src/components/UserProfile

# Search for validation messages in all locale files
fd -e json . public/locales | xargs cat

# Search for form field enums or constants
rg "enum|const.*Status" -A 3 -B 3 src/

Length of output: 122957

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

11-14: LGTM! Clear and user-friendly validation messages

The validation messages are well-structured, consistent, and provide clear guidance to users, which aligns perfectly with the PR's objective of simplifying error feedback.

Let's verify the usage of these messages in the codebase:

✅ Verification successful

Let me verify the usage of these validation messages by checking the form validation implementation.


Validation messages are properly integrated and used in error handling

The validation messages are correctly implemented in the error handler utility (src/utils/errorHandler.tsx), which displays appropriate toast notifications using the translation keys. The error handler properly maps backend validation errors to user-friendly messages for phone number, education grade, employment status, and marital status fields.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if these validation messages are properly integrated with form validation logic

# Search for validation message keys in the codebase
echo "Checking usage of validation messages in components:"
rg -l "(invalidPhoneNumber|invalidEducationGrade|invalidEmploymentStatus|invalidMaritalStatus)"

# Look for form validation logic
echo -e "\nChecking form validation implementation:"
ast-grep --pattern 'const $_ = useTranslation($$$)' -A 5

Length of output: 93686


Script:

#!/bin/bash
# Search for validation message usage in form validation logic
echo "Checking form validation implementations:"
rg -A 5 "invalidPhoneNumber|invalidEducationGrade|invalidEmploymentStatus|invalidMaritalStatus" src/utils/errorHandler.tsx

Length of output: 856

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

11-16: Well-aligned with PR objectives for simplified error handling.

The new error messages perfectly match the PR objectives by:

  • Providing clear, user-friendly feedback
  • Addressing one validation issue at a time
  • Clearly indicating the required action

11-16: Verify consistency across all language files.

Let's ensure these new error messages are consistently implemented across all language files (en, fr, hi, zh) with equivalent meanings.

✅ Verification successful

All error messages are properly translated and consistent across language files

The verification shows that all the new error messages (invalidPhoneNumber, invalidEducationGrade, invalidEmploymentStatus, invalidMaritalStatus, error400, defaultError) are:

  • Present in all language files (en, fr, hi, sp, zh)
  • Properly translated with equivalent meanings
  • Consistently formatted in valid JSON
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if all language files contain the same keys and are properly formatted

# List of new keys to verify
KEYS=("invalidPhoneNumber" "invalidEducationGrade" "invalidEmploymentStatus" "invalidMaritalStatus" "error400" "defaultError")

# Find all error.json files
echo "Checking all locale files..."
fd "errors.json" public/locales

# Verify each key exists in all locale files
for key in "${KEYS[@]}"; do
  echo -e "\nChecking key: $key"
  rg -l "\"$key\":" public/locales/*/errors.json
done

# Validate JSON format
echo -e "\nValidating JSON format..."
fd "errors.json" public/locales -x jq '.' {} \; >/dev/null

Length of output: 3109


Script:

#!/bin/bash
# Let's check the actual content of these error messages to verify translations
echo "=== English (en) error messages ==="
jq -r 'select(.invalidPhoneNumber, .invalidEducationGrade, .invalidEmploymentStatus, .invalidMaritalStatus, .error400, .defaultError) | .' public/locales/en/errors.json

echo -e "\n=== French (fr) error messages ==="
jq -r 'select(.invalidPhoneNumber, .invalidEducationGrade, .invalidEmploymentStatus, .invalidMaritalStatus, .error400, .defaultError) | .' public/locales/fr/errors.json

echo -e "\n=== Hindi (hi) error messages ==="
jq -r 'select(.invalidPhoneNumber, .invalidEducationGrade, .invalidEmploymentStatus, .invalidMaritalStatus, .error400, .defaultError) | .' public/locales/hi/errors.json

echo -e "\n=== Chinese (zh) error messages ==="
jq -r 'select(.invalidPhoneNumber, .invalidEducationGrade, .invalidEmploymentStatus, .invalidMaritalStatus, .error400, .defaultError) | .' public/locales/zh/errors.json

Length of output: 21107

src/utils/errorHandler.tsx (2)

13-13: LGTM! Good practice for error message extraction.

Extracting the error message into a variable improves code readability and prevents repeated property access.


18-31: Consider using error codes instead of string matching.

The current implementation relies on string matching which is fragile and could break if the backend error messages change. Using error codes or constants would be more maintainable.

Let's verify the backend error messages:

public/locales/hi/errors.json Outdated Show resolved Hide resolved
public/locales/en/errors.json Outdated Show resolved Hide resolved
src/utils/errorHandler.tsx Outdated Show resolved Hide resolved
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: 2

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

24-26: Enhance 400 error handling with more context

The generic handling of status code 400 might hide specific validation errors from the user.

Consider extracting and displaying specific validation errors from the 400 response:

if (errorMessage.includes('status code 400')) {
  try {
    const errorData = JSON.parse(errorMessage);
    // Extract specific validation errors if available
    const validationErrors = errorData.errors || [];
    validationErrors.forEach(error => 
      toast.error(tErrors(error.code) || tErrors('error400'))
    );
  } catch {
    toast.error(tErrors('error400'));
  }
}

13-28: Add error boundaries for React components

While the current error handler manages API errors, it doesn't handle React component errors.

Consider implementing React Error Boundaries:

interface ErrorBoundaryProps {
  children: React.ReactNode;
  fallback: React.ReactNode;
}

class ErrorBoundary extends React.Component<ErrorBoundaryProps, { hasError: boolean }> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error: Error) {
    return { hasError: true };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    errorHandler(null, error);
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback;
    }
    return this.props.children;
  }
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1a4ee76 and 61948bc.

📒 Files selected for processing (1)
  • src/utils/errorHandler.tsx (1 hunks)

src/utils/errorHandler.tsx Show resolved Hide resolved
src/utils/errorHandler.tsx Outdated Show resolved Hide resolved
@bandhan-majumder
Copy link
Contributor Author

I can use map. But it will still use includes method. As backend is returning a string of all errors combined, I need to check it that way.

@palisadoes
Copy link
Contributor

Please fix the failing tests

@bandhan-majumder
Copy link
Contributor Author

bandhan-majumder commented Nov 28, 2024

  1. graphql error may arise because the graphql setup of talawa-api is not completed yet.
  2. This is treating the errors.json files as TypeScript files, it's showing the "key" : "values" relations as not used in a function call. JSON files should be ignored while checking the linting as it expects every expression to be used in a function call or assignment.
    Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions

Please let me know if I need to change anything.

@palisadoes
Copy link
Contributor

Please submit your PRs against our develop-postgres branch. To facilitate our reviews, the source and target branches in the PR must be different. The failing test indicates this. Closing.

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