首页 > 解决方案 > 如何在本机反应中显示网络错误消息

问题描述

我有一个 react native 函数,它使用 fetch 函数来发布一些数据。问题是我无法提醒响应错误消息。我的错误代码是 400。这是我的代码:

fetch(conf.getsignUpURL(), {
              method: "POST",
              headers: {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json',
              },
              body: JSON.stringify(data)
          })
              .then(function (response) {
                  if (!response.ok)
                  {
                     let error = new Error(response.statusText);
                      throw error;
                  }else
                  {
                      return response.json();
                  }

              })
              .then(async function (data) {
                  //something
              }).catch( (error) => {
              alert(error.message);
          });

运行后会提示空。

标签: react-nativeexception-handlingfetchthrow

解决方案


fetch(conf.getsignUpURL(), {
              method: "POST",
              headers: {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json',
              },
              body: JSON.stringify(data)
          })
              .then(function (response) {

                // Here I added the alert
                alert(JSON.stringify(response))

                  if (!response.ok)
                  {
                     let error = new Error(response.statusText);
                      throw error;
                  }else
                  {
                      return response.json();
                  }

              })
              .then(async function (data) {

                // Here I added the alert
                alert(JSON.stringify(data))

                  //something
              }).catch( (error) => {
              alert(error.message);
          });

推荐阅读