Generate new Error and get this error in the catch of the controller

0

In my API made in Node , I create the user from a service:

exports.create = async(data) => {
    try {

        let verifica = await UsuarioModel.findByUsername(data.username);

        if(verifica) throw new Error('Já existe um usuário cadastrado com este username');
        return 'verificado'; // o código é apenas um trecho

    } catch (error) {
        return error;
    }
}

In the controller, I just call this service as follows:

exports.create = async(req, res) => {
    try {
        let retorno = await UsuarioServices.create(req.body);

        console.log(retorno);


        res.status(201).send(retorno);
    } catch (error) {
        res.status(500).send(error);
    }
}

However, the error generated in the service if there is already a user with the same username is not shown in the return of the request, only in console.log() is that I can get the error generated in the service. How do I pass this error forward and show it as a return of the request?

    
asked by anonymous 18.11.2018 / 23:01

1 answer

1

You are throwing an error inside a try block. Its error is captured by the block itself, and then returned with a return . At this point your error is just a message, it does not make sense to return a message if you want to catch the error by the function that is invoking UsuarioServices.create .

exports.create = async(data) => {    
    if (await UsuarioModel.findByUsername(data.username))
        throw new Error('Já existe um usuário cadastrado com este username');

    return 'verificado'; // o código é apenas um trecho    
}
exports.create = async(req, res) => {
    try {
        let retorno = await UsuarioServices.create(req.body);
        console.log(retorno);    
        res.status(201).send(retorno);

    } catch (error) {
        res.status(500).send(error.message);
    }
}
    
18.11.2018 / 23:36