AlexMI
AlexMI

Reputation: 986

How to properly pass custom errors from Backend (Express) to Frontend (Vue)

I am developing a basic Node app and I am facing a problem that I think is not new but I don't understand which is the proper way to solve. I need to handle those errors that are not generated by code, network or database but needed by the logic of the application. As an example I use the already registered user but the same handling will be needed in different case in the application.

I start from the method in login component:

register () {
  API
    .register(this.credentials)
    .then(
      data => {
        this.user = data;
      },
      error => {
        this.error = error;
      })
    .catch(error => {
      this.error = error;
    });
},

The API is:

register (credentials) {
 return Axios
  .post('/auth/register',credentials)
  .then(response => {
    return response.data;
  })
},

The Backend is:

router.post('/auth/register',(req,res) => {
User.findOne({where:{username:req.body.username}})
  .then(user => {
    if (!user) {
      User
        .create(req.body)
        .then(user => {
          res.send(user);
        })
    } else {
      throw 'Username already exists';
    }
  });
});

What I expect is that the error

throw 'Username already exists';

(but it can be No data found for your search) is passed back to the component that catch it and show the error instead the registerd user. I try adding the catch after every then or using res.send({error:...}) instead of throw but in this way the component shows the error message as user object.

Upvotes: 3

Views: 3323

Answers (1)

TheWildHealer
TheWildHealer

Reputation: 1616

Use HTTP Status Codes to propagate errors through HTTP:

Backend:

router.post('/auth/register',(req,res) => {
console.log('backend register 3',req.body);
User.findOne({where:{username:req.body.username}})
  .then(user => {
    if (!user) {
      User
        .create(req.body)
        .then(user => {
          console.log('backend register 4',req.body);
          res.send(user);
        })
    } else {
      res.status(409).send('User already exists')
    }
  });
});

Fronted:

register (credentials) {
 return Axios
  .post('/auth/register',credentials)
  .then(response => {
    return response.data;
  })
  .catch(err => {
    processError(err);
  })
},

Upvotes: 4

Related Questions