Home > Mobile >  Show an errorModal if there is a server error
Show an errorModal if there is a server error

Time:02-02

I'm wanting to display an Error modal that will render if there is a server error on submit of a panel. I'm wondering whether the correct way to go about it is in the catch statement?

basic code I have is:

useEffect(() => { if (!isOpen) setShowSuccessConfirmation(false); }, [isOpen]);

const enableSubmission = currentDocuments.length > 0;

const submitPanel = () => { const documentIds = currentDocuments.map(doc => doc.documentId);

setIsSubmitting(true);

Trading(panelState!.code, documentIds)
  .then(() => {
    setShowSuccessConfirmation(true);
  })
  .finally(() => {
    setIsSubmitting(false);
  });

};

in my panel I have my ErrorModal:

        <ErrorModal show={showModal} onClose={() => { setShowModal(false) }} />

what I think I want to do is add a catch like:

.catch((error) => {
    if (error.status === 500) {
      setShowModal(true);
      setShowSuccessConfirmation(false)
    }
  })

I don't get any errors but this doesn't seem to work.

CodePudding user response:

A 500 status code is not an error, it is just a way for the server to tell you what happen while the request was being processed in the same way that 200, 204, 302, etc are. I've had projects where only 204 where valid statuses codes and other where any 3XX status code was considered an error.

If you want to show a modal under those conditions, you will need to detect this situation which means that you will need to do the check in the then:

Trading(panelState!.code, documentIds)
  .then((response) => {
    // Here I am assuming you have access to the response object
    if (response.status === 500) {
      setShowModal(true);
      setShowSuccessConfirmation(false)
    } else {
      setShowSuccessConfirmation(true);
    }
  })
  .finally(() => {
    setIsSubmitting(false);
  });

Alternatively, you can throw an error in the then part and catch it in the catch:

Trading(panelState!.code, documentIds)
  .then((response) => {
    // Here I am assuming you have access to the response object
    if (response.status === 500) {
      throw new Error(response.status);
    }
    
    setShowSuccessConfirmation(true);
  })
  .catch((error) => {
    // You can access the status code from here with error.message
      setShowModal(true);
      setShowSuccessConfirmation(false)
  })
  .finally(() => {
    setIsSubmitting(false);
  });

For a real error to be caught in catch, a communication problem should happen (f.e. a timeout). Which means that you need to consider such errors when/if you use the catch part.

  • Related