9

I'm wrapping an imported SDK class with a Proxy so that I can eventually catch RequestExceptions, i.e. when there is no network connection to display error popups.

The app is working without issues in remote debugging mode, however, when I disable it the error Can't find Variable: Proxy is thrown. Do I need to import this explicitly somehow? Or is there an alternative method to wrap a class so that I can catch all of its exceptions?

Below is the code for the Proxy wrapper.

import Backend from 'backend-sdk';

import RequestException from 'backend-sdk/src/exceptions/RequestException';

let handler = {
  get: (target, name, receiver) => {
    try {
      return Reflect.get(target, name, receiver);
    } catch (e) {
      if (e instanceof RequestException) {
        console.error(e);
        //TODO Add a toast notification for failed API requests
      } else {
        throw e;
      }
    }
  }
};

export default new Proxy(new Backend(), handler);
Mastergalen
  • 4,289
  • 3
  • 31
  • 35

2 Answers2

8

Proxy is not pollyfilled in react native by default. It works in chrome debugger because react native uses chrome js engine during debugging see Document on js environment. You may try using Proxy pollyfill.

while1
  • 3,320
  • 19
  • 12
  • Thanks, worked perfectly. I also had to polyfill Reflect: https://github.com/tvcutsem/harmony-reflect – Mastergalen Aug 11 '16 at 10:13
  • @Mastergalen could you please post some more comments about how you made it work with proxy-polifill + harmony-reflect. I think Android still that issue and it's not really working for me. – Evos Apr 27 '18 at 15:14
2

Note that as of react-native 0.59, react-native on Android now uses a more modern version of JavaScriptCore that includes Proxy support.

ArthurDenture
  • 2,161
  • 1
  • 16
  • 15
  • Thank you for this! Does the same apply to iOS? I'm using react-native 0.63 - i can't find specifcially where 0.59 says they support iOS – Noitidart Sep 25 '22 at 19:04
  • 1
    I believe that react-native iOS uses the native JavaScriptCore bundled with iOS, and that has supported Proxy for a long time now. (https://caniuse.com/proxy) – ArthurDenture Sep 28 '22 at 21:31