How can I throw custom error when someone tries to mutate an object that is frozen by me?

I need to freeze an object/array so it cannot be mutated in any way. Object.freeze() is almost perfect:

const arr = [];
const obj = { foo: "bar" };
let frozenArr = Object.freeze(arr);
let frozenObj = Object.freeze(obj);

// Uncaught TypeError: Cannot add property 0, object is not extensible

// Uncaught TypeError: Cannot add property x, object is not extensible
frozenObj.x = 'abc';

The problem is, I would like to throw a custom error that will explain to the developer WHY an object is frozen, how to deal with it, etc...

I was thinking of using Proxy or Object.defineProperties() and manually throwing errors in setters, but I don't want to reinvent the wheel, hence my question here. Maybe someone already have a solution.



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.