Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Narrowing down error type in catch

For this piece of code

try {   throw new CustomError(); } catch (err) {   console.log(err.aPropThatDoesNotExistInCustomError); } 

err is any and doesn't trigger type errors. How can it be narrowed down to the type that error is expected to be?

like image 266
Estus Flask Avatar asked Jul 28 '17 18:07

Estus Flask


People also ask

What is the type of error in catch?

catch can only handle errors that occur in valid code. Such errors are called “runtime errors” or, sometimes, “exceptions”. That's because the function itself is executed later, when the engine has already left the try... catch construct.

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.

Can we write 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.


1 Answers

You need to perform a check yourself to narrow inside a catch block. The compiler does not know or believe that err will definitely be a CustomError:

try {   throw new CustomError(); } catch (err) {   console.log('bing');   if (err instanceof CustomError) {     console.log(err.aPropThatIndeedExistsInCustomError); //works     console.log(err.aPropThatDoesNotExistInCustomError); //error as expected   } else {     console.log(err); // this could still happen   } } 

For example, here's my evil implementation of CustomError:

class CustomError extends Error {   constructor() {     super()     throw new Error('Not so fast!');  // The evil part is here   }   aPropThatIndeedExistsInCustomError: string; } 

In this case err will not be a CustomError. I know, that's probably not going to happen, but the point is that the compiler won't do this narrowing automatically for you. If you are absolutely sure of the type, you can assign to another variable:

try {   throw new CustomError(); } catch (_err) {   const err: CustomError = _err;   console.log(err.aPropThatDoesNotExistInCustomError); // errors as desired } 

but remember that you could possibly run into trouble at runtime if you're mistaken about the type.

Good luck!

P.S.: See TypeScript issues #8677 and #9999 for more information.

like image 75
jcalz Avatar answered Sep 19 '22 10:09

jcalz