1

I am trying to do error handling for POST with the same user email with the following(using superagent):

export function signUpUser(userData) {
  return async dispatch => {
    try {
      const currentUser = await request.post(`${url}/signup`).send(userData);
      set(window.localStorage, 'x-auth', currentUser);
      dispatch(signUpSuccessObject(userData));
    } catch (error) {
      dispatch(signUpFailObject(error));
    }
  };
}

I want to get the following which I can see in my network tab:

{"name":"SequelizeUniqueConstraintError","errors":[{"message":"email must be unique","type":"unique violation","path":"email","value":"leo@fsl.co","origin":"DB","instance":

But instead all I get is:

Bad Request

My controller for API:

User.create(
      Object.assign(req.body, {
        password: bcrypt.hashSync(req.body.password, 10),
      })
    )
      .then(() => {
        const myToken = jwt.sign({email: req.body.email}, 'leogoesger');
        res.status(200).send(myToken);
      })
      .catch(err => res.status(400).send(err));
  },
leogoesger
  • 3,476
  • 5
  • 33
  • 71
  • Status 400 (aka "Bad request") indicates a client error (such as malformed syntax, size too large, etc.). This is not really the source of your error, in particular in case of a DB field that fails validation. Have you tried sending back a different status code to see if that's what's blocking you from seeing the error client-side? My guess is, the browser's default behavior might take over on some specific status codes, and 400 might be one of them? – Thomas Hennes Nov 28 '17 at 01:29
  • Apparently, the choice of what status code to use for a situation like yours is up for debate. See https://stackoverflow.com/questions/19671317/400-bad-request-http-error-code-meaning - some very interesting answers & comments there. – Thomas Hennes Nov 28 '17 at 01:37
  • 1
    The problem is `error` in dispatch. What I should have used is `error.response`. It is weird how it works different from `onSuccess` case. – leogoesger Nov 28 '17 at 03:11

2 Answers2

2

https://github.com/visionmedia/superagent/issues/1074

^^ Used this as a reference.

Basically, I need error.response. This will give me the entire object, which will allow me to get access to the error message.

So full working code would be:

export function signUpUser(userData) {
  return async dispatch => {
    try {
      const currentUser = await request
        .post(`${url}/signup`)
        .send(userData)
        .type('json');
      set(window.localStorage, 'x-auth', currentUser);
      dispatch(signUpSuccessObject(userData));
    } catch (e) {
      dispatch(signUpFailObject(e.response.body));
    }
  };
}
leogoesger
  • 3,476
  • 5
  • 33
  • 71
1

res.send() will send plain text/html responses.

Use res.json(myToken) and res.status(400).json(err) for a JSON API.

Matt
  • 68,711
  • 7
  • 155
  • 158