P
P
Pogran2016-08-24 11:28:09
React
Pogran, 2016-08-24 11:28:09

How to make error handling through axios last?

For example, I send a request to an address via axios
axios.post('/api/users', {username: ''});
handler looks like this

let router = express.Router();

function validateInput(data) {
    let errors = {};

    if(Validator.isNull(data.username)) {
        errors.username = 'This field is required';
    }

    return {
        errors,
        isValid: isEmpty(errors)
    }
}

router.post('/', (req, res) => {
    const {errors, isValid} = validateInput(req.body);

    if(!isValid) {
        res.status(400).json(errors);
    }
});

export default router;

How to make this handler through Promise and return the result correctly. And then in axios through then(get response successful) and catch(get errors)
axios is used last

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2016-08-24
@Pogran

And why through Promise? You have the usual synchronous verification code and that's it. Let it be:

...
router.post('/', (req, res) => {
    const {errors, isValid} = validateInput(req.body);

    if(!isValid) {
        return res.status(400).json(errors);
    } else {
        return res.status(200).json({data: 'bla-bla-bla'})
    }
});
...

Well, axios itself is "promisified" in advance. Took an example from the documentation :
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

If I understood you correctly, then you would like to use then/catch with axios, but you think that if the express router does not return a promise, this is impossible? No, it's not.
If it returns an error, catch will be executed; if it returns "ok", then will be executed. I can't tell from memory, but res.status(400) might work like then because it's not an "erroneous" value returned. Then just throw an exception instead of res.status(400) (like new Error ...) and then the catch will definitely work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question