[JS / NODEJS] Error declaring a variable within a try catch block

0

----- help.js ----

exports.run = async (command_s, Discord, message, client) => {
  // temporal
  const command = "profile";

  function string(){
      try{x = require('./commands/utility/${command}'+'.js'); var result = x;return result;}catch(err){};
      try{y = require('./command/fun/${command}'+'.js'); var result = y;return result;}catch(err){};
  }

  const x = await string()
  console.log(x)
  const final_message = x.info()
  console.log(final_message)

}

I want to make a system that checks in which "folder" the file is located by means of a try / catch, but when calling the variable 'result' it returns me: "undefined". Then I want to be able to call from that var "x" the function 'info ()', which returns a string: ------ profile.js -----

function info(){
   return "Obtén la información sobre tu perfil"}
    
asked by guskikalola 25.12.2018 в 21:25
source

1 answer

1

You have the idea, but you need to polish a little more. First you must use the nested try/catch blocks, that is, one inside another.

I told you what I would do, and I hope it helps you:

exports.run = async (command_s, Discord, message, client) => {
  // temporal
  const command = "profile";

  // Nuestra función acepta como parámetro un valor
  // así podremos reutilizarla si hiciera falta
  function string(command) {
    try {
      
      // Declaro mi variable dentro de la función
      const x = require('./commands/utility/${command}'+'.js'); // <== no se si realmente necesitas agregar la extensión
      // Si 'require()' se ejecuta correctamente devuelvo la variable
      // Pero si hay un error, el bloque 'catch' se ejecutará
      return x;
      } catch(err1) { // Notemos que este error se llama 'err1'
        // Si llegamos aqui, entonces lo anterior falló
        console.log('err1: ', err1.message);
        
        // Aqui ponemos nuestro segundo 'try/catch'
        // a esto se le llama 'anidado'
        try {
        
          // Nuevamente declaro la variable local
          const y = require('./command/fun/${command}'+'.js'); // <== no se si realmente necesitas agregar la extensión
          
          // Si 'require()' se ejecuta correctamente devuelvo la variable
          // Pero si hay un error, el bloque 'catch' se ejecutará
          return y;
          } catch(err2) { // Notemos que este error se llama 'err2'
      
            // Si llegamos aqui, entonces lo anterior falló
            // Devolvemos null (aunque puedes devolver otra cosa
            // Eso lo decides segun la lógica de tu programa)
            console.log('err2: ', err2.message);
            return null;
          } // Fin catch(err2)
        } // Fin catch (err1)
    }//Fin funcion string()
  
  // Ahora podemos declarar una variable que contenga
  // el resultado de nuestra funcion, la llamare perfil
  
  const perfil = await string(command);
  
  // Ahora verificamos que efectivamente modulo contiene un módulo
  
  if (!perfil) {
    console.log('Hubo un error al hacer \'require()\'');
  } else {
    perfil.info();
  }
  
} // Fin async

So you already have a very basic way to check which folder your file is in.

There are many tools you could use for this task, but you may only need this to solve your problem.

Greetings.

    
answered by 07.01.2019 / 21:10
source