Skip to main content
Use this API to listen for unhandled Promise rejections. The callback triggers when a Promise without a rejection handler is rejected.

Parameters

PropertyTypeRequiredDescription
callbackFunctionYesHandler executed when an unhandled rejection occurs

Callback Parameters

PropertyTypeDescription
reasonStringThe rejection reason (typically an error object)
promisePromiseThe rejected Promise instance

Code Example

Basic Usage

App({
  onShow() {
    my.onUnhandledRejection((res) => {
      console.log('Unhandled rejection reason:', res.reason);
      console.log('Rejected promise:', res.promise);
    });
  }
});

Error Logging

App({
  onLaunch() {
    my.onUnhandledRejection((res) => {
      // Log unhandled rejections
      this.logRejection({
        reason: res.reason,
        timestamp: Date.now()
      });
    });
  },

  logRejection(data) {
    my.request({
      url: 'https://api.example.com/errors/rejections',
      method: 'POST',
      data: data
    });
  }
});

Development Debugging

App({
  onLaunch() {
    my.getRunScene({
      success: ({ envVersion }) => {
        if (envVersion === 'develop') {
          my.onUnhandledRejection((res) => {
            // Show detailed info in development
            my.alert({
              title: 'Unhandled Promise Rejection',
              content: String(res.reason)
            });
          });
        }
      }
    });
  }
});

Common Causes

Unhandled Promise rejections typically occur when:
// This will trigger onUnhandledRejection
my.request({
  url: 'https://api.example.com/data'
}).then((res) => {
  console.log(res);
});
// Missing .catch()

// Correct approach
my.request({
  url: 'https://api.example.com/data'
}).then((res) => {
  console.log(res);
}).catch((err) => {
  console.error('Request failed:', err);
});
// This will trigger onUnhandledRejection
async function fetchData() {
  const res = await my.request({ url: '...' });
  return res.data;
}

// Correct approach
async function fetchData() {
  try {
    const res = await my.request({ url: '...' });
    return res.data;
  } catch (err) {
    console.error('Failed:', err);
    return null;
  }
}
// Error in .then() without .catch()
fetchData()
  .then((data) => {
    throw new Error('Processing failed');
  });

// Correct approach
fetchData()
  .then((data) => {
    throw new Error('Processing failed');
  })
  .catch((err) => {
    console.error('Chain error:', err);
  });
Always add .catch() handlers to your Promises or use try/catch with async/await to prevent unhandled rejections.

my.offUnhandledRejection

Stop listening for unhandled rejections

my.onError

Listen for JS errors