Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass catch error inside function into parent

I have this sample couple lines of code, wanna know how exactly the logic below:

try {
  var response = child()
  console.log('why here')
} catch (err) {
  console.log('should show this', err)
}

function child() {
  try {
    throw new Error('oops');
  } catch (err) {
    console.log('child error', err)
  }
}

The expected result is to console should show this together with err, but it returned console why here

like image 706
Hariawan Avatar asked Jun 05 '18 16:06

Hariawan


People also ask

How do you catch an error thrown in a function?

You can propagate the error from a function to the code that calls that function, handle the error using a do - catch statement, handle the error as an optional value, or assert that the error will not occur.

How do you handle errors in catch block?

You can put a try catch inside the catch block, or you can simply throw the exception again. Its better to have finally block with your try catch so that even if an exception occurs in the catch block, finally block code gets executed. Finally block may not get executed in certain exceptions.

Can we use error in catch block?

You can use it in a catch clause, but you should never do it! If you use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors. Errors are thrown by the JVM to indicate serious problems that are not intended to be handled by an application.

Does catch stop execution?

All methods in the call stack between the method throwing the exception and the method catching it have their execution stopped at the point in the code where the exception is thrown or propagated.


1 Answers

You merely throw the same error again. The catch allows you to handle it, you want to log it, or prevent it and etc. Or you can just rethrow it. When you throw new Error(). You're creating a new instance of an Error. The throw is what makes it able to do what it does. But you can declare Errors without throwing them.

let e = new Error('my error :D'); //Do some stuff...... throw e;

if you throw e and it's caught, e is still an instance of an error. You can just throw it again and again until the app crashes :D

But it's a good way to log details about the stack trace, local variables and etc. Most professional teams will have their own custom console logger that allows the console logs to be saved to a data base and reviewed later. This logging event might occur at every try catch and add minor details to the log that'll help with debugging a massive and complicated project. Additionally, in a lot strongly typed languages, you can have multiple catches that allow different responses depending on the error type (ReferenceError, TypeError, etc). So you can catch one error, analyze why it happened and maybe throw your own custom error so that a higher up process handles it accordingly :o

try 
{
  var response = child()
  console.log('why here')
} 
catch (err) 
{
  console.log('should show this', err)
}

function child() 
{
  try 
  {
    throw new Error('oops');
  } 
  catch (err) 
  {
    console.log('child error', err)
    throw err;
  }
}

One Take on Handling Error By Type in Javascript

There are better ways to do this, but this is just an example. Imagine if we had a function that fired off for each switch case instead of just a console log. Depending on the type of error, a difference response is initiated. A problem that occur with this is if you have multiple layers of inheritance within Error classes.

function ValidateClassType(obj, classDef)
{
  if(!obj || !classDef)
  {
    throw new ReferenceError("1 or More Parameters is Undefined");
  }
  if(typeof classDef != 'function')
  {
    throw new TypeError("classDef Must be a Callable Constructor.")
  }
  
  let isInstanceOf = obj instanceof classDef;
  if(!isInstanceOf)
  {
    throw new TypeError("Invalid Class Type for Operation");
  }
}

try
{
  ValidateClassType(1, null);
}
catch(err)
{
  let errType = err.constructor.name;
  switch(errType)
  {
    case 'ReferenceError':
      console.log('A Reference Error Occured.');
      break;
    case 'TypeError':
      console.log('A type Error Occured.');
      break;
    default:
      console.log('An Unhandled Error Occurred.');
  }
}
like image 106
Eddie D Avatar answered Oct 16 '22 02:10

Eddie D