简体   繁体   English

如何通过expressjs的响应在前端捕获错误?

[英]How catch error in the front-end from response of expressjs?

My problem is the next: 我的问题是下一个:

 //express server app.post('/register', (req, res) => { const { password, passwordConfirm } = req.body; if (password === passwordConfirm) { //... } else { res.status(400).json("Passwords aren't matching") } }) //react function onSubmitSignIn = () => { const { password, passwordConfirm } = this.state; let data = new FormData(); data.append('password', password); data.append('passwordConfirm', passwordConfirm); fetch('http://localhost:3001/register', { method: 'post', body: data }) .then(response => response.json()) .then(user => { //logs error message here console.log(user) }) //but I want to catch it here, and set the message to the state .catch(alert => this.setState({alert})) } 

When I send the status code, and the message from express as the response, the front-end obviously recognize it as the response, that's why it logs the message to the console as "user". 当我发送状态代码,并将来自express的消息作为响应时,前端显然将其识别为响应,这就是为什么它将消息以“用户”身份记录到控制台的原因。 But how to send error which goes to the catch function? 但是如何发送到catch函数的错误呢?

fetch will really only error if it for some reason can't reason the API. 如果由于某种原因无法fetch API,则fetch实际上只会出错。 In other words it will error on network errors. 换句话说,它将因网络错误而出错。 It will not explicitly error for non 2XX status codes. 2XX状态代码不会明确显示错误。

You need to check the ok property as described here: 您需要按照以下说明检查ok属性:

-- -

fetch('http://localhost:3001/register', {
    method: 'post',
    body: data
 })
 .then(response => {
     if (!response.ok) {
         throw new Error('my api returned an error')
     }
     return response.json()
 })
 .then(user => {

      console.log(user)
  })
  .catch(alert => this.setState({alert}))

The problem is, that fetch is not recognizing the HTTP errors as Promise rejections. 问题是, fetch未将HTTP错误识别为Promise拒绝。

The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally, and it will only reject on network failure or if anything prevented the request from completing. 即使响应是HTTP 404或500,从fetch()返回的Promise也不会拒绝HTTP错误状态。相反,它将正常解析,并且仅在网络故障或任何阻止请求完成的情况下拒绝。

( Source ) 来源

You can checkout the linked source of the fetch repo which also states a suggestion for handling HTTP error statuses. 您可以检fetch存仓库的链接源,该源还指出了处理HTTP错误状态的建议。

What if you throw an error : 如果抛出错误怎么办:

app.get("/", function (req, res) {
  throw new Error("BROKEN"); // Express will catch this on its own.
});

And then catch this error in the front end ? 然后在前端捕获此错误?

See here for reference 请参阅此处以供参考

EDIT 编辑

Maybe should you return the error with return next() so that the rest of the code is not processed in the server method : 也许您应该使用return next()返回错误,以便在服务器方法中不处理其余代码:

 app.get("/", function (req, res) {
     return next(new Error('BROKEN'));
 });
//express server
app.post('/register', (req, res) => {
 try {
  const {
   password,
   passwordConfirm
  } = req.body;
  if (password === passwordConfirm) {
   //...
  } else {
   res.status(400).json("Passwords aren't matching")
  }
 } catch (error) {
  res.status(500).send(error);
 }
})
//react function
onSubmitSignIn = () => {
 const {
  password,
  passwordConfirm
 } = this.state;
 let data = new FormData();
 data.append('password', password);
 data.append('passwordConfirm', passwordConfirm);

 fetch('http://localhost:3001/register', {
   method: 'post',
   body: data
  })
  .then(response => response.json())
  .then(user => {
   //logs error message here
   console.log(user)
  })
  //but I want to catch it here, and set the message to the state
  .catch(alert => this.setState({
   alert
  }))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM