Vanilla JS – Wrap Object Methods in Try/Catch to Handle Errors in JavaScript

[ad_1]

I created the below function recently to encapsulate error handling logic for multiple JS object methods in a single place.

The function wraps all top-level methods of the provided object (myObject) in a try/catch block to handle all errors the same way. You could use the same approach to wrap javascript methods with any cross-cutting functionality (e.g. logging).

Object.entries() converts the provided object into an array of key/value pairs so the Array.map() method can be called.

Object.fromEntries() converts the provided array of key/value pairs back into an object.

function wrapObjectMethods(myObject) {
    return Object.fromEntries(
        Object.entries(myObject).map(([key, value]) => {
            const isMethod = typeof value === 'function';
            if (isMethod) {
                return [key, wrapMethod(value)];
            } else {
                return [key, value];
            }
        })
    );

    function wrapMethod(method) {
        return async (...args) => {
            try {
                return await method(...args);
            } catch (err) {
                // ERROR!
                console.error(err);
            }
        };
    }
}

 

To add error handling to an existing object I call the function like this:

const objectWithErrorHandling = wrapObjectMethods(anObject);

 

Table of Contents

Need Some Vanilla JS Help?

Search fiverr for freelance Vanilla JS developers.

Follow me for updates

On Twitter or RSS.

When I’m not coding…


Me and Tina are on a motorcycle adventure around Australia.

Come along for the ride!

Comments




[ad_2]

Share this content:

I am a passionate blogger with extensive experience in web design. As a seasoned YouTube SEO expert, I have helped numerous creators optimize their content for maximum visibility.

Leave a Comment