Crispy
Crispy

Reputation: 422

Javascript - error handling stopping code

quick basic question,

When setting up guildmember.timout with discord.js v13, it gives an example with .then(console.log) and .catch(console.error). Using the example, the code will continue after the .catch.

      muteMember
        .timeout(time, reason)
        .catch((error) => {
          return errors(client, message, args, "mute", error, true);
        });

      muteMember.send ... 

At the moment it will run the errors function then continue onto the code after the .catch, for example muteMember.send. What's the best way to have it "stop" after it runs what is inside of the .catch? Thank you in advance

Upvotes: 1

Views: 371

Answers (4)

MrMythical
MrMythical

Reputation: 9041

You can make it return a falsy if the error occurs, then check if it is falsy, and return if it is.

let isModified = await muteMember
        .timeout(time, reason)
        .catch((error) => {
            errors(client, message, args, "mute", error, true)
            return false;
        })
if (!isModified) return;

Upvotes: 1

Brendan Bond
Brendan Bond

Reputation: 1890

muteMember.timeout() returns a Promise, so any code that you want to run after the promise resolves you should wrap in a then() block:

muteMember
        .timeout(time, reason)
        .then((member) => {
          // code that depends on successfully timing out a member
          muteMember.send....
        })
        .catch((error) => {
          // only runs if there's an error
          errorcheck = true
          return errors(client, message, args, "mute", error, true);
        });

You can also use the more modern and readable async/await syntax:

const myAsyncFunction = async () => {
  try {
    const member = await muteMember.timeout(time, reason);
    // code that depends on successfully timing out a member
    muteMember.send....
  } catch (error) {  
    // only runs if there's an error
    errorcheck = true
    return errors(client, message, args, "mute", error, true);
  }
}
    

Upvotes: 0

Finbar
Finbar

Reputation: 1353

The return statement only returns out of the #catch callback. Handle the promise with a #then callback, thats where you want your code to run when its successful.

muteMember
    .timeout(time, reason)
    .catch((error) => {
        //error
        errorcheck = true
        return errors(client, message, args, "mute", error, true);
    })
    .then(() => {
        //success
    })

Upvotes: 0

User81646
User81646

Reputation: 743

You can use async-await with try-catch:

async function myFunction()
{
  try
  {
    await muteMember.timeout(time, reason)
    // throws an error if it fails -- jumps to the catch block

    muteMember.send...
  }
  catch(error)
  {
    errorcheck = true
    errors(client, message, args, "mute", error, true);
    // and whatever other error handling you would like
  }
}

Upvotes: 0

Related Questions