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

change console.log to console.error in try catch blocks and removed logs to show up in production #4284

Merged
merged 4 commits into from
Jul 9, 2024

Conversation

lovelgeorge99
Copy link
Collaborator

@lovelgeorge99 lovelgeorge99 commented Jun 17, 2024

Summary by CodeRabbit

  • New Features

    • Updated recurring donation messages in multiple languages for better clarity.
  • Bug Fixes

    • Improved error logging throughout the application by changing console.log statements to console.error.
  • Chores

    • Included a conditional check to override console.log in production environments, enhancing performance and security.

Copy link

vercel bot commented Jun 17, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
giveth-dapps-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 9, 2024 1:25pm

Copy link
Contributor

coderabbitai bot commented Jun 17, 2024

Walkthrough

The overall change involves updating various messages and logs in the codebase. Text messages for recurring donations were clarified across three languages, while numerous console log statements were modified from console.log to console.error, indicating an enhanced approach to error logging. Additionally, an environment-based conditional was introduced to override console logging in a production setting.

Changes

Files/Paths Change Summary
lang/ca.json, lang/en.json, lang/es.json Updated recurring donation maximum messages to be clearer about the need to reload the balance for more donations.
pages/_app.tsx Introduced a conditional check to override console.log in production environment.
pages/donate/[slug].tsx, pages/success/[slug].tsx, pages/verification/[slug]/index.tsx, scripts/g... Changed console.log to console.error for error logging.
src/apollo/apolloClient.ts, src/components/USDInput.tsx, src/components/cards/MintCard.tsx, src/components/menu/NotificationButtonWithMenu.tsx Updated console.log to console.error for error visibility during specific operations.
src/components/modals/... In multiple modals (EditUserModal.tsx, MintModal.tsx, SearchModal.tsx, etc.), console.log statements were changed to console.error for better error handling.
src/context/... Within context files (profile.context.tsx, project.context.tsx), console.log was replaced with console.error for error logging.
src/features/user/user.thunks.ts Changed console.log statements to console.error within error handling blocks for various asynchronous functions.
src/helpers/network.ts, src/hooks/... Updated console.log to console.error for error handling in several hooks and helper functions.
src/lib/stakingPool.ts Changed console.log to console.error for error logging in various staking pool related functions.
src/services/... In multiple service files (donation.ts, passport.ts), replaced console.log with console.error for error visibility.

Poem

In code's quiet meadows, changes sweep,
Logging errors now, we’re more alert and deep.
Messages clearer, a guide for donation delight,
Console logs switch, from mere log to error bright.
Production smiles, silencing needless calls,
Progress dances through digital halls.
🐇✨🚀


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 120c8ef and d7c663d.

Files selected for processing (17)
  • pages/_app.tsx (1 hunks)
  • pages/verification/[slug]/index.tsx (1 hunks)
  • src/apollo/apolloClient.ts (2 hunks)
  • src/components/modals/SearchModal.tsx (1 hunks)
  • src/components/modals/deactivateProject/DeactivateProjectIndex.tsx (1 hunks)
  • src/components/views/create/AlloProtocol/AlloProtocolModal.tsx (1 hunks)
  • src/components/views/donate/OnTime/DonateModal.tsx (1 hunks)
  • src/components/views/donate/Recurring/ModifySuperToken/DepositSuperToken.tsx (2 hunks)
  • src/components/views/donate/Recurring/ModifySuperToken/WithDrawSuperToken.tsx (1 hunks)
  • src/components/views/donate/Recurring/RecurringDonationModal/RecurringDonationModal.tsx (1 hunks)
  • src/components/views/userProfile/donationsTab/recurringTab/ModifyStreamModal/UpdateStreamInnerModal.tsx (1 hunks)
  • src/context/project.context.tsx (1 hunks)
  • src/hooks/useCreateEvmDonation.tsx (2 hunks)
  • src/hooks/useCreateSolanaDonation.tsx (1 hunks)
  • src/lib/stakingPool.ts (7 hunks)
  • src/services/donation.ts (6 hunks)
  • src/services/passport.ts (2 hunks)
Files skipped from review due to trivial changes (13)
  • pages/verification/[slug]/index.tsx
  • src/components/modals/SearchModal.tsx
  • src/components/modals/deactivateProject/DeactivateProjectIndex.tsx
  • src/components/views/create/AlloProtocol/AlloProtocolModal.tsx
  • src/components/views/donate/OnTime/DonateModal.tsx
  • src/components/views/donate/Recurring/ModifySuperToken/DepositSuperToken.tsx
  • src/components/views/donate/Recurring/ModifySuperToken/WithDrawSuperToken.tsx
  • src/components/views/donate/Recurring/RecurringDonationModal/RecurringDonationModal.tsx
  • src/components/views/userProfile/donationsTab/recurringTab/ModifyStreamModal/UpdateStreamInnerModal.tsx
  • src/context/project.context.tsx
  • src/hooks/useCreateSolanaDonation.tsx
  • src/services/donation.ts
  • src/services/passport.ts
Additional comments not posted (13)
src/apollo/apolloClient.ts (2)

125-125: Change console.log to console.error for better error visibility.

The change from console.log to console.error ensures that errors are more noticeable in the logs, which is particularly useful for debugging.


137-137: Change console.log to console.error for better error visibility.

The change from console.log to console.error ensures that network errors are more noticeable in the logs, which is particularly useful for debugging.

src/hooks/useCreateEvmDonation.tsx (3)

157-157: Change console.log to console.error for better error visibility.

The change from console.log to console.error ensures that errors during the transaction sending process are more noticeable in the logs, which is particularly useful for debugging.


166-166: Change console.log to console.error for better error visibility.

The change from console.log to console.error ensures that errors related to the transaction name are more noticeable in the logs, which is particularly useful for debugging.


173-173: Change console.log to console.error for better error visibility.

The change from console.log to console.error ensures that rejected transactions are more noticeable in the logs, which is particularly useful for debugging.

pages/_app.tsx (1)

81-83: Override console.log in production environment.

This change ensures that console.log statements do not appear in the production environment, which helps in keeping the production console clean.

src/lib/stakingPool.ts (7)

84-84: Change console.log to console.error for better error visibility.

The change from console.log to console.error ensures that errors during fetching total supply and reward rate are more noticeable in the logs, which is particularly useful for debugging.


553-553: Change console.log to console.error for better error visibility.

The change from console.log to console.error ensures that errors during token approval are more noticeable in the logs, which is particularly useful for debugging.


574-574: Change console.log to console.error for better error visibility.

The change from console.log to console.error ensures that errors during token wrapping are more noticeable in the logs, which is particularly useful for debugging.


609-609: Change console.log to console.error for better error visibility.

The change from console.log to console.error ensures that errors during token staking are more noticeable in the logs, which is particularly useful for debugging.


635-635: Change console.log to console.error for better error visibility.

The change from console.log to console.error ensures that errors during token unwrapping are more noticeable in the logs, which is particularly useful for debugging.


745-745: Change console.log to console.error for better error visibility.

The change from console.log to console.error ensures that errors during token locking are more noticeable in the logs, which is particularly useful for debugging.


777-777: Change console.log to console.error for better error visibility.

The change from console.log to console.error ensures that errors during fetching GIVpower are more noticeable in the logs, which is particularly useful for debugging.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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
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: 7

Outside diff range and nitpick comments (13)
pages/donate/[slug].tsx (1)

Line range hint 28-28: Consider adding dispatch to the dependency array of this useEffect to comply with React's exhaustive-deps rule.

-	}, []);
+	}, [dispatch]);
pages/verification/[slug]/index.tsx (1)

Line range hint 83-96: Remove redundant else clauses to simplify conditional rendering.

- else if (!isEnabled) {
+ if (!isEnabled) {
- else if (!isSignedIn) {
+ if (!isSignedIn) {
- else if (!isUserRegistered(userData)) {
+ if (!isUserRegistered(userData)) {
- else if (!allowVerification) {
+ if (!allowVerification) {
src/features/user/user.thunks.ts (1)

Line range hint 196-204: Consider removing the unnecessary else clauses as indicated by the static analysis tool. These clauses are redundant because the previous branches already terminate the control flow (either by returning or rejecting a promise).

- else {
+ // Removed unnecessary else clause
src/components/views/verification/PersonalInfo.tsx (1)

Line range hint 84-91: The static analysis tool suggests removing unnecessary else clauses. This can simplify the control flow and improve the readability of the code.

- else {
+ // Removed unnecessary else clause

Also applies to: 89-91

pages/_app.tsx (2)

Line range hint 214-214: The dangerouslySetInnerHTML property is used here for injecting analytics script. While this is a common pattern, it's generally advised to avoid using dangerouslySetInnerHTML due to the risk of XSS attacks. Consider alternatives like using external scripts with nonces or hashes if possible.

- dangerouslySetInnerHTML={{ __html: renderSnippet() }}
+ // Consider safer alternatives for script injection
Tools
Biome

[error] 82-82: This function expression can be turned into an arrow function. (lint/complexity/useArrowFunction)

Function expressions that don't use this can be turned into arrow functions.
Safe fix: Use an arrow function instead.


Line range hint 176-176: The useEffect hook is missing dependencies. This could lead to unexpected behavior if any of the missing dependencies change. Consider adding asPath, pathname, query, and router to the dependency array.

- }, []);
+ }, [asPath, pathname, query, router]);
Tools
Biome

[error] 82-82: This function expression can be turned into an arrow function. (lint/complexity/useArrowFunction)

Function expressions that don't use this can be turned into arrow functions.
Safe fix: Use an arrow function instead.

src/components/views/donate/RecurringDonationModal/RecurringDonationModal.tsx (1)

Line range hint 199-201: Remove unnecessary else clause after early return statements to simplify control flow.

- else {
-   throw new Error('Super token not found');
- }
src/lib/helpers.ts (6)

Line range hint 2-2: Rename the local unescape import to avoid confusion with the global unescape function.

- import unescape from 'lodash/unescape';
+ import lodashUnescape from 'lodash/unescape';

Line range hint 105-105: Encapsulate variable declarations within blocks in switch cases to limit their scope.

case ChainType.EVM:
+ {
    const chainId = (chain as Chain)?.id;
    if (!config.EVM_NETWORKS_CONFIG[chainId]) return '';
    return `${config.EVM_NETWORKS_CONFIG[chainId]?.blockExplorers?.default.url}/address/${address}`;
+ }

case ChainType.SOLANA:
+ {
    const url = `https://explorer.solana.com/address/${address}`;
    switch (chain) {
        case WalletAdapterNetwork.Mainnet:
            return url;
        case WalletAdapterNetwork.Devnet:
            return `${url}?cluster=devnet`;
        case WalletAdapterNetwork.Testnet:
            return `${url}?cluster=testnet`;
    }
    return '';
+ }

Also applies to: 110-110


Line range hint 238-241: Remove unnecessary else block due to previous branches containing return statements.

- else {
-   return '';
- }

Line range hint 281-281: Use optional chaining to simplify the code.

- if (!networkId || !txHash || !config.EVM_NETWORKS_CONFIG[networkId])
+ if (!networkId || !txHash || !config.EVM_NETWORKS_CONFIG[networkId]?.blockExplorers?.default.url)

Line range hint 555-555: Replace Function type with a more specific function signature to avoid potential bugs and improve type safety.

- export function pollEvery(fn: Function, delay: any) {
+ export function pollEvery(fn: (params: any) => { request: () => Promise<any>; onResult: (result: any) => void; }, delay: number) {

Also applies to: 559-559


Line range hint 576-576: Define a more specific object shape instead of using the generic Object type.

- export function isObjEmpty(obj: Object) {
+ export function isObjEmpty(obj: Record<string, unknown>) {

@@ -609,7 +609,7 @@ export const unwrapToken = async (
value: 0n,
});
} catch (error) {
console.log('Error on unwrapping token:', error);
console.error('Error on unwrapping token:', error);
Copy link
Contributor

Choose a reason for hiding this comment

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

Logging and capturing exceptions are correctly implemented. It might be beneficial to add specific error handling depending on what can go wrong during the unwrapping process.

- console.error('Error on unwrapping token:', error);
+ console.error('Error on unwrapping token:', error);
+ // Add error-specific handling or user notification here

Committable suggestion was skipped due to low confidence.

@@ -583,7 +583,7 @@
value: 0n,
});
} catch (error) {
console.log('Error on stake token:', error);
console.error('Error on stake token:', error);
Copy link
Contributor

Choose a reason for hiding this comment

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

Good practice to log and capture exceptions. Consider adding more specific error handling or recovery logic based on the type of error.

- console.error('Error on stake token:', error);
+ console.error('Error on stake token:', error);
+ // Add recovery or retry logic here

Committable suggestion was skipped due to low confidence.

@@ -728,7 +728,7 @@
value: 0n,
});
} catch (error) {
console.log('Error on locking token:', error);
console.error('Error on locking token:', error);
Copy link
Contributor

Choose a reason for hiding this comment

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

The error handling through logging and capturing the exception is consistent with other parts of the code. Consider implementing additional logic to manage or mitigate the error.

- console.error('Error on locking token:', error);
+ console.error('Error on locking token:', error);
+ // Consider adding logic to handle or mitigate this error

Committable suggestion was skipped due to low confidence.

@@ -537,7 +537,7 @@
return false;
}
} catch (error) {
console.log('Error on Approve', error);
console.error('Error on Approve', error);
Copy link
Contributor

Choose a reason for hiding this comment

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

The conversion of logging to console.error is appropriate for error handling. However, consider handling the error more gracefully by potentially retrying or providing feedback to the user, depending on the context.

- console.error('Error on Approve', error);
+ console.error('Error on Approve', error);
+ // Consider retrying the approval or notifying the user based on the error type

Committable suggestion was skipped due to low confidence.

@@ -78,6 +78,9 @@
if (process.env.NEXT_PUBLIC_ENV === 'development') {
return snippet.max(opts);
}
if (process.env.NEXT_PUBLIC_ENV === 'production') {
console.log = function () {};
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider converting the anonymous function used for overriding console.log to an arrow function for consistency and to adhere to modern JavaScript practices.

- console.log = function () {};
+ console.log = () => {};
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
console.log = function () {};
console.log = () => {};
Tools
Biome

[error] 82-82: This function expression can be turned into an arrow function. (lint/complexity/useArrowFunction)

Function expressions that don't use this can be turned into arrow functions.
Safe fix: Use an arrow function instead.

@@ -88,7 +88,7 @@ export const retryFetchSolanaTransaction = async (
solanaConnection,
txHash,
).catch(error => {
console.log(
console.error(
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper handling of null values for txHash in error messages.

- console.error('Attempt', i, 'Fetching Transaction Error:', error, txHash);
+ console.error('Attempt', i, 'Fetching Transaction Error:', error, txHash || 'undefined');
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
console.error(
console.error('Attempt', i, 'Fetching Transaction Error:', error, txHash || 'undefined');

@@ -59,7 +59,7 @@
const transaction = await getTransaction(wagmiConfig, {
hash: txHash,
}).catch(error => {
console.log(
console.error(
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper handling of null values for txHash in error messages.

- console.error('Attempt', i, 'Fetching Transaction Error:', error, txHash);
+ console.error('Attempt', i, 'Fetching Transaction Error:', error, txHash || 'undefined');
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
console.error(
console.error('Attempt', i, 'Fetching Transaction Error:', error, txHash || 'undefined');

Copy link
Collaborator

@RamRamez RamRamez left a comment

Choose a reason for hiding this comment

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

Great! Thanks @lovelgeorge99

@RamRamez
Copy link
Collaborator

RamRamez commented Jul 9, 2024

@lovelgeorge99 There are some conflicts. Please solve them, then fill free to merge it

@lovelgeorge99 lovelgeorge99 merged commit 2b80e80 into develop Jul 9, 2024
3 checks passed
@lovelgeorge99 lovelgeorge99 deleted the remove-console-logs-from-production#3585 branch July 9, 2024 13:25
@coderabbitai coderabbitai bot mentioned this pull request Sep 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

2 participants