Skip to content

Commit

Permalink
feat: onUnhandledRejection 支持core-js promise polyfill
Browse files Browse the repository at this point in the history
  • Loading branch information
mackwang committed Jan 17, 2025
1 parent 581523c commit 31280e7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
23 changes: 13 additions & 10 deletions packages/core/src/platform/env/index.ios.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isNumber, isString } from '@mpxjs/utils'
import { createI18n } from '../builtInMixins/i18nMixin'

export function init (Mpx) {
Expand Down Expand Up @@ -30,25 +31,27 @@ function initGlobalErrorHandling () {
})
}

function onUnhandledRejection (event) {
if (global.__mpxAppCbs && global.__mpxAppCbs.rejection && global.__mpxAppCbs.rejection.length) {
global.__mpxAppCbs.rejection.forEach((cb) => {
cb(event)
})
} else {
console.warn(`UNHANDLED PROMISE REJECTION ${isNumber(event.id) ? '(id:' + event.id + ')' : ''}: ${event.reason}\n`)
}
}
const rejectionTrackingOptions = {
allRejections: true,
onUnhandled (id, error) {
if (global.__mpxAppCbs && global.__mpxAppCbs.rejection && global.__mpxAppCbs.rejection.length) {
global.__mpxAppCbs.rejection.forEach((cb) => {
cb(error, id)
})
} else {
console.warn(`UNHANDLED PROMISE REJECTION (id: ${id}): ${error}\n`)
}
onUnhandledRejection({ id, reason: error, promise: null })
}
}

// 支持 core-js promise polyfill
const oldOnUnhandledRejection = global.onunhandledrejection
global.onunhandledrejection = function onunhandledrejection (event) {
// event = { promise, reason }
rejectionTrackingOptions.onUnhandled(null, event.reason)
oldOnUnhandledRejection.apply(this, event)
onUnhandledRejection(event)
oldOnUnhandledRejection.call(this, event)
}
if (global?.HermesInternal?.hasPromise?.()) {
global.HermesInternal.enablePromiseRejectionTracker?.(rejectionTrackingOptions)
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/platform/env/index.web.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ function initGlobalErrorHandling () {
window.addEventListener('unhandledrejection', (event) => {
if (global.__mpxAppCbs && global.__mpxAppCbs.rejection && global.__mpxAppCbs.rejection.length) {
global.__mpxAppCbs.rejection.forEach((cb) => {
cb(event.reason, event.promise)
cb(event)
})
} else {
console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}\n`)
Expand Down

0 comments on commit 31280e7

Please sign in to comment.