Home > other >  How to catch an err in node.js?
How to catch an err in node.js?

Time:11-01

How can I catch an err in node.js Here's my code:

const { Client, Message, MessageEmbed} = require("discord.js")
const translate = require('@iamtraction/google-translate')
module.exports = {
  name: "ترجم",
  description: `يترجم اللغه فقط أستعمل !translate "الكلمه/الجمله يلي بدك تترجمها"`,
  aliases: ['translate'],
  run: async (client, message, args) => {
    const query = args.join(" ")
    const lang = args[0]
    if(!query) return message.reply('Please specify a text to translate');
    const translated = await translate(query, {to: lang });
    message.reply(translated.text);
  },
};

It works when I type in chat: !translate ar hello But when I type: !translate "not a real lang" hello It shutdowns with the error: Error: The language 'not a real lang' is not supported

I tried .catch I tried if and else I tried "try" ...

CodePudding user response:

async functions return a value only if no error occurred. If something goes wrong an error is thrown that has to be catched.

You call the async function that errs with the await keyword, so you have to surround that with a try{ } catch (e) {} block like this:

try {
   const translated = await translate(query, {to: lang });
   message.reply(translated.text);
} catch (e) {
   message.reply('Translation failed: '   e.message);
}

Since you take care of another possible error one line above, you could wrap the whole thing into a try-catch-block and take care of all kinds of errors in a unified way:

const { Client, Message, MessageEmbed} = require("discord.js")
const translate = require('@iamtraction/google-translate')
module.exports = {
  name: "ترجم",
  description: `يترجم اللغه فقط أستعمل !translate "الكلمه/الجمله يلي بدك تترجمها"`,
  aliases: ['translate'],
  run: async (client, message, args) => {
    try {
      const query = args.join(" ")
      const lang = args[0]
      if(!query) throw new Error('Please specify a text to translate');
      const translated = await translate(query, {to: lang });
      message.reply(translated.text);
    } catch (e) {
      if (message) {
        message.reply('Translation failed: '   e.message);
      }
    }
  },
};

This way you will get a meaningful reply in any case (as long as you have a valid message). For example maybe args is not an array.

CodePudding user response:

In the @iamtraction/google-translate documentation, there is clear exemple of how to catch the error, so it should work with .then/.catch

I tried .catch I tried if and else I tried "try" ...

I don't know how you tried them, but it would be usefull if you show us the examples of your tries.

  • Related