简体   繁体   中英

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". But how to send error which goes to the catch function?

fetch will really only error if it for some reason can't reason the API. In other words it will error on network errors. It will not explicitly error for non 2XX status codes.

You need to check the ok property as described here:

--

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.

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.

( Source )

You can checkout the linked source of the fetch repo which also states a suggestion for handling HTTP error statuses.

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 :

 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
  }))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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