diff --git a/packages/plugin-react-native-unhandled-rejection/rejection-handler.js b/packages/plugin-react-native-unhandled-rejection/rejection-handler.js index c784bda4be..fb3cf1894f 100644 --- a/packages/plugin-react-native-unhandled-rejection/rejection-handler.js +++ b/packages/plugin-react-native-unhandled-rejection/rejection-handler.js @@ -18,20 +18,40 @@ module.exports = { severityReason: { type: 'unhandledPromiseRejection' } }, 'promise rejection tracking', 1) client._notify(event) - // adding our own onUnhandled callback means the default log message doesn't happen, so make it happen here - if (typeof __DEV__ !== 'undefined' && __DEV__) logError(id, error) + // adding our own onUnhandled callback means the default handler doesn't get called, so make it happen here + if (typeof __DEV__ !== 'undefined' && __DEV__) rnInternalOnUnhandled(id, error) } }) return () => rnPromise.disable() } } -// this function is copied in from the promise module, since it's not exported and we can't reference it: -// https://github.com/then/promise/blob/91b7b4cb6ad0cacc1c70560677458fe0aac2fa67/src/rejection-tracking.js#L101-L107 -function logError (id, error) { - console.warn('Possible Unhandled Promise Rejection (id: ' + id + '):') - var errStr = (error && (error.stack || error)) + '' - errStr.split('\n').forEach(function (line) { - console.warn(' ' + line) - }) +// This is a direct copy (with flow types removed) from RN internal code. In v0.64+ it is possible to reference, but in +// older versions we can't access it so simply have to copy it. +// https://github.com/facebook/react-native/blob/4409642811c787052e0baeb92e2679a96002c1e3/Libraries/Promise.js#L21-L46 +const rnInternalOnUnhandled = (id, rejection) => { + let message + let stack + + const stringValue = Object.prototype.toString.call(rejection) + if (stringValue === '[object Error]') { + message = Error.prototype.toString.call(rejection) + const error = rejection + stack = error.stack + } else { + try { + message = require('pretty-format')(rejection) + } catch { + message = + typeof rejection === 'string' + ? rejection + : JSON.stringify(rejection) + } + } + + const warning = + `Possible Unhandled Promise Rejection (id: ${id}):\n` + + `${message ?? ''}\n` + + (stack == null ? '' : stack) + console.warn(warning) }