Error Handling via Try & Catch Proxy in Javascript

Tugay İlik
2 min readDec 1, 2018
Simple javascript error

Errors can happen in any software. To keep your software/program working, you may want catch them, hide them or track them, or sometimes you want to give information to your clients when error happens, it’s up to you. But sometimes, those errors can’t be easy to catch. It can oblige you to wrap your code with several try catch blocks to preventing functionality loss. Adding those blocks brings more complexity, extra code logics and decreases your code cleanness.

Instead of doing this, you can wrap your class functions with a proxy.

Let’s get to work and understand how we can achieve this easily with a small proxy function!

1.First, we define proxy function that takes an argument, which is the class that we are going to wrap its methods. In javascript, we can access all properties of a class over its prototype property.

2. If the class doesn’t have any property except constructor, we don’t need to wrap anything. Since constructor property is always exists on class creation we are handling this case too.

3. It’s time to define our handler method for wrapping function executions. What it does, simply wraps given function with try catch block and calls it with given arguments.

4. Now we have handler method. It’s time to wrap functions in given class with this wrapper function and override class functions with wrapped one.

Object.getOwnPropertyDescriptors method returns a property descriptor for an own property (that is, one directly present on an object and not in the object’s prototype chain) of a given object. Via using this, we will access all properties of given super class. Then we will filter constructor and non-function properties. The rest will be overridden with wrapper function.

6. That’s it, we are done! Now we can wrap our classes with our proxy helper;

tryCatchProxy(MyClass);

After doing this, method executions of super class, will be executed in wrapper function and if something goes wrong, it will be get into catch block! 🕺

Hope you enjoyed reading and it helps you ! ✴️

A working example can be found in this gist;

https://gist.github.com/tugayilik/f574827ef31caf61b92de79b64dfa47e

--

--