Gergő Horváth
Gergő Horváth

Reputation: 3705

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?

Upvotes: 2

Views: 7612

Answers (4)

Manishkumar Bhavnani
Manishkumar Bhavnani

Reputation: 57

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

Upvotes: 0

Ramiz Wachtler
Ramiz Wachtler

Reputation: 5683

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.

Upvotes: 2

Cisco
Cisco

Reputation: 23070

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

Upvotes: 6

Louis
Louis

Reputation: 438

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

Upvotes: 0

Related Questions