Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(react-native): Copy RN's internal logging for unhandled rejections #1419

Merged
merged 1 commit into from
Jun 7, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}