Generate new Error and get this error in the controller catch

Asked

Viewed 48 times

0

In my API made in Node, i make user creation 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 as a return of the request?

  • It seems that you are using exceptions where you should not, it hardly makes sense to capture an exception that you yourself create, aside from the fact that an invalid username is not something exceptional, it is something normal, which will probably occur frequently

1 answer

1

You’re throwing an error inside a block try. Your mistake is captured by the block itself, and then returned with a return. At this point your error is just a message, it makes no sense to return a message if you want to capture the error by the function you are 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);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.