BioDrop icon indicating copy to clipboard operation
BioDrop copied to clipboard

[BUG] needs proper error handling in manage form section

Open badrivlog opened this issue 3 years ago β€’ 17 comments

Description

We have lots of AJAX call in pages/account/manage section and we are calling fetch() function. The problem is here that by default the fetch function doesn't reject the promise if we get back an error status code, in that case, we should reject the promise and throw an actual error and handle the rejected promise.

The downside of not handling a rejected promise in fetch call is that if the request fails for any reason, such as a network error or server-side error, the code does not handle the error gracefully. As a result, the application may not provide appropriate feedback or error handling to the user.

Without proper error handling, it becomes challenging to identify the cause of the issue. Debugging the code and fixing the problem becomes more complex, as there is no specific error message or indication of what went wrong.

To address this issue, it is important to handle rejected promises appropriately. This can involve displaying error messages to the user.

Screenshots

No response

Additional information

want to fix this issue

badrivlog avatar Jul 10 '23 18:07 badrivlog

To reduce notifications, issues are locked until they are https://github.com/EddieHubCommunity/LinkFree/labels/%F0%9F%8F%81%20status%3A%20ready%20for%20dev and to be assigned. You can learn more in our contributing guide https://github.com/EddieHubCommunity/LinkFree/blob/main/CONTRIBUTING.md

github-actions[bot] avatar Jul 10 '23 18:07 github-actions[bot]

The issue has been unlocked and is now ready for dev. If you would like to work on this issue, you can comment to have it assigned to you. You can learn more in our contributing guide https://github.com/EddieHubCommunity/LinkFree/blob/main/CONTRIBUTING.md

github-actions[bot] avatar Jul 16 '23 19:07 github-actions[bot]

Thank you for the suggestion πŸ‘ I think 1 location of code should be updated and then we can discuss further before implementing it to other areas of the code

eddiejaoude avatar Jul 16 '23 19:07 eddiejaoude

I want to work in this issue.

Dobariya-Nishant avatar Jul 17 '23 05:07 Dobariya-Nishant

My idea is, If the request fails for any reason, such as a network error or server-side error, then reject that promise by throwing an appropriate error message and handle it in the catch block.

One possible solution might be this- (example code: pages/account/manage/profile.js)

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const res = await fetch(`${BASE_URL}/api/account/manage/profilesf`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ name, bio, tags, layout }),
      });

      if (!res.ok) {
        const update = await res.json();
        throw new Error(update.error || update.message || res.statusText);
      }
      setShowNotification({
        show: true,
        type: "success",
        message: "Profile updated",
        additionalMessage: "Your profile has been updated successfully",
      });
    } catch (err) {
      setShowNotification({
        show: true,
        type: "error",
        message: "Profile update failed",
        additionalMessage: `Please check the fields: ${err.message}`,
      });
    }
}; 

what do you think?

badrivlog avatar Jul 17 '23 05:07 badrivlog

const handleSubmit = (e) => {
   e.preventDefault();
   fetch(`${BASE_URL}/api/account/manage/profilesf`, {
       method: "PUT",
       headers: {
           "Content-Type": "application/json",
       },
       body: JSON.stringify({ name, bio, tags, layout }),
   })
   .then(async(res) => {
       if (!res.ok) {
           const update = await res.json();
           throw new Error(update.error || update.message || res.statusText);
       }
   })
   .then((data) => {
       setShowNotification({
           show: true,
           type: "success",
           message: "Profile updated",
           additionalMessage: "Your profile has been updated successfully",
       });
   })
   .catch((err) => {
       setShowNotification({
           show: true,
           type: "error",
           message: "Profile update failed",
           additionalMessage: `Please check the fields: ${err.message}`,
       });
   })  
};

@badrivlog When I saw this issue, I thought handling it this way but your try catch and async wait wait is a better approach in my opinion because it's easier to understand.

Dobariya-Nishant avatar Jul 17 '23 08:07 Dobariya-Nishant

const handleSubmit = (e) => {
   e.preventDefault();
   fetch(`${BASE_URL}/api/account/manage/profilesf`, {
       method: "PUT",
       headers: {
           "Content-Type": "application/json",
       },
       body: JSON.stringify({ name, bio, tags, layout }),
   })
   .then(async(res) => {
       if (!res.ok) {
           const update = await res.json();
           throw new Error(update.error || update.message || res.statusText);
       }
   })
   .then((data) => {
       setShowNotification({
           show: true,
           type: "success",
           message: "Profile updated",
           additionalMessage: "Your profile has been updated successfully",
       });
   })
   .catch((err) => {
       setShowNotification({
           show: true,
           type: "error",
           message: "Profile update failed",
           additionalMessage: `Please check the fields: ${err.message}`,
       });
   })  
};

@badrivlog When I saw this issue, I thought handling it this way but your try catch and async wait wait is a better approach in my opinion because it's easier to understand.

@Dobariya-Nishant I think code you wrote is not correct

badrivlog avatar Jul 17 '23 09:07 badrivlog

@badrivlog sorry I don't know, it would be great if you correct my code.

Dobariya-Nishant avatar Jul 17 '23 09:07 Dobariya-Nishant

@badrivlog sorry I don't know, it would be great if you correct my code.

I think you should need to know how promise works. (note: please don't comment issues that are unrelated as this creates extra noise and confusion)

If you need any help- EddieHub Discord might be better https://discord.gg/44dXjyWB

badrivlog avatar Jul 17 '23 11:07 badrivlog

Yes we use async/await in our project and we are keen to keep things consistent πŸ‘ thanks for the collaboration everyone, great to see different perspectives πŸ’ͺ

@badrivlog that looks good πŸ‘ I will assign it to you

eddiejaoude avatar Jul 18 '23 08:07 eddiejaoude

Thank you for the suggestion πŸ‘ I think 1 location of code should be updated and then we can discuss further before implementing it to other areas of the code

Please take a look my draft PR I created. I have improved the error handling functionality and updated in one location of code.

should I implementing it to other areas of the code?

badrivlog avatar Jul 23 '23 09:07 badrivlog

Thank you for the suggestion πŸ‘ I think 1 location of code should be updated and then we can discuss further before implementing it to other areas of the code

Please take a look my draft PR I created. I have improved the error handling functionality and updated in one location of code.

should I implementing it to other areas of the code?

I will ask the other maintainers to take a look, I don't see a big benefit, it looks very much the same to me and focused on form validation - so wouldn't work for other http requests πŸ€”

I think the part we could use is wrapping the http request in a try/catch

eddiejaoude avatar Jul 23 '23 10:07 eddiejaoude

Yes, we could wrap the http request in a try/catch and handles the error, that might be a solution. But this approach will produce lots of duplicate code, even of this is kind of repetitiveπŸ€”

In opinion it's really a bit cumbersome to having to do all these step all the time. Instead it would be good to actually create ourselves a really nice utility function for api request. And that utility function will wrap up the fetch the error handling, and also the conversion to JSON.

export async function sendRequest(requestConfig) { 
   try { 
     const res = await fetch(requestConfig.url, { 
       method: requestConfig.method ? requestConfig.method : "GET", 
       headers: requestConfig.headers ? requestConfig.headers : {}, 
       body: requestConfig.body ? JSON.stringify(requestConfig.body) : null, 
     }); 
     const data = await res.json(); 
     if (!res.ok) { 
       let errMessage = res.statusText; 
       if (data.message) { 
         if (typeof data.message === "string") errMessage = data.message; 
         else { 
           errMessage = Object.keys(data.message) 
             .map((val) => `${val} is required`) 
             .join(", "); 
         } 
       } 
       if (data.error) { 
         errMessage = data.error; 
       } 
  
       throw new Error(`Request failed! ${errMessage}.`); 
     } 
     return data; 
   } catch (err) { 
     console.error(err); 
     throw err; 
   } 
 }

The sendRequest will accept any kind of api request and when there is an error in this fetch, it will throw a new error and it also immediately converts the response to JSON The sendRequest function abstract all this functionality into one nice function that we can use all over our project.

badrivlog avatar Jul 25 '23 07:07 badrivlog

And that utility function will wrap up the fetch the error handling, and also the conversion to JSON.

But part of that code is specific to form validation and not other requests

eddiejaoude avatar Jul 25 '23 09:07 eddiejaoude

And that utility function will wrap up the fetch the error handling, and also the conversion to JSON.

But part of that code is specific to form validation and not other requests

Hey, thank you for correcting meπŸ’ͺ I have pushed new changes to my PR, please take a look πŸ™

What's next?

badrivlog avatar Jul 25 '23 18:07 badrivlog

Hi @eddiejaoude ,

I hope you're doing well. I've submitted a pull request for Handling rejected promise and I would really appreciate your feedback. Your expertise would be invaluable in ensuring the quality and functionality of the code changes.

Please take a moment to review the pull request at https://github.com/EddieHubCommunity/LinkFree/pull/8283 and share your thoughts. Your insights and suggestions will help me to improve the codebase and deliver a better product.

Thank you in advance for your time and effort!

badrivlog avatar Aug 05 '23 11:08 badrivlog

Thanks @badrivlog sure I will take a look and ask the maintainers to also as this is a challenging topic πŸ‘

eddiejaoude avatar Aug 05 '23 17:08 eddiejaoude