First log exceptions before catching

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the exceptions category.

Last Updated: 2024-04-19

In project T, I couldn't get images to upload to firebase and the error stack traces were cryptic:

Code:

catch(() => {
  return console.error("Error encountered when taking photo")
})

Stack tracce: javascript - node_modules/react-native/Libraries/LogBox/LogBox.js:148:8 in registerError - node_modules/react-native/Libraries/LogBox/LogBox.js:59:8 in errorImpl - node_modules/react-native/Libraries/LogBox/LogBox.js:33:4 in console.error - node_modules/expo/build/environment/react-native-logs.fx.js:27:4 in error * components/Camera.tsx:53:15 in camera.takePictureAsync.then._catch$argument_0 - node_modules/react-native/node_modules/promise/setimmediate/core.js:37:13 in tryCallOne - node_modules/react-native/node_modules/promise/setimmediate/core.js:123:24 in setImmediate$argument_0 - node_modules/react-native/Libraries/Core/Timers/JSTimers.js:130:14 in _callTimer - node_modules/react-native/Libraries/Core/Timers/JSTimers.js:181:14 in _callImmediatesPass - node_modules/react-native/Libraries/Core/Timers/JSTimers.js:441:30 in callImmediates - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:3

The fix was passing in the error to be logged (i.e. don't just give the generic message, since that hides information)

catch((error) => {
  return console.error("Error encountered when taking photo", error)
})
Error encountered when taking photo, FirebaseStorageError {
  "code_": "storage/invalid-format",
  "message_": "Firebase Storage: String does not match format 'data_url': Must be formatted 'data:[<mediatype>][;base64],<data>",
  "name_": "FirebaseError",
  "serverResponse_": null,
}
- node_modules/react-native/Libraries/LogBox/LogBox.js:148:8 in registerError
...

Corollary: Do not trust the error message an exception leaves

In React Native I was trying to upload a base64 image to firebase storage. It failed with "Invalid character found" so I messed around with encoding for a while.

Ultimately the problem was the React Native env did not include Base 64 conversion function atob normally present in core JS.

Here is the firebase code

var bytes;
try {
  bytes = atob(string);
}
catch (e) {
  throw errorsExports.invalidFormat(format, 'Invalid character found');
}

The exception in my case should really have read atob not defined etc. I should have been vigilant to catch-all handlers that obscure info.