在React js中提取时如何隐藏控制台状态错误消息? [英] How to hide console status error message while fetching in React js?

查看:261
本文介绍了在React js中提取时如何隐藏控制台状态错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的React应用程序中,我正在使用fetch()从我的API中获取数据,如果我的数据库中存在该域的网站,则_callAPI()函数将获取domain参数并调用API.如果存在,则返回网站的对象,否则返回500.因此,直到使用fetch(),我才能弄清楚该网站是否存在.问题在于,每次fetch()都找不到任何东西时,它会引发以下内容:

In my React app, I'm using fetch() to get data from my API, _callAPI() function gets domain parameter and call API if a website of the domain exists in my DB. If it exists, it returns the website's object, otherwise it returns 500. So, I can't figure out if the website exists until I use fetch(). The problem is that every time fetch() doesn't find anything, it throws the following:

container.jsx:25 GET http://localhost:3000/boutiques/detail/?q = testdomain.com 500(内部服务器错误)

container.jsx:25 GET http://localhost:3000/boutiques/detail/?q=testdomain.com 500 (Internal Server Error)

当找不到很多网站时,控制台日志中会包含该错误消息.有没有一种方法在提取时会忽略此类消息?

When it doesn't doesn't find a lot of websites, the console log is packed with that error message. Is there a way to ignore that sort of message while fetching?

fetch()

fetch()

_callApi = () => {
    const { domain } = this.props;

    return fetch(`/boutiques/detail/?q=${domain}`)
      .then(response => {
        if (response.status === 500) {
          return 500;
        }
        return response.json();
      })
      .then(json => json)
      .catch(err => console.log(err));
  };

推荐答案

如果要忽略浏览器错误:

很遗憾,此操作无法完成,因为 控制台是由Chrome本身打印的.压制此类消息 已经争论了很多年,但是共识似乎是 消息是可取的

Unfortunately, this cannot be done, as this type of message in the console is printed by chrome itself. Repressing this type of message has been debated for years, but the consensus seems to be that this message is desirable

信用.

如果要在控制台中忽略未处理"错误:

您始终可以按如下所示静默前端错误:

You can always mute the error on front-end, as follows:

.catch(err => { const mute = err })

但是最好以某种方式通知用户该错误,而不要采取这种变通办法.

But it would be better to notify somehow the user about the error and not doing such workarounds.

另外,最好让服务器在响应中返回错误消息,并在前端进行处理.

Also it would better your server to return an error message in the response and on the front-end side you will proceed it.

考虑到您的情况,服务器最好使用状态码400进行响应.这是HTTP错误代码及其用途:

Looking into your case, it may be better the server to response with status code 400. Here are the HTTP error codes and their purpose:

  • 4xx (客户端错误):请求包含错误的语法或不能为 完成
  • 5xx (服务器错误):服务器无法完成 显然有效的请求
  • 4xx (Client Error): The request contains bad syntax or cannot be fulfilled
  • 5xx (Server Error): The server failed to fulfill an apparently valid request

这篇关于在React js中提取时如何隐藏控制台状态错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆