Use this API to listen for JavaScript errors that occur during Mini Program execution. This allows you to implement custom error handling and logging strategies.
Parameters
Property Type Required Description callback Function Yes Handler executed when a JS error occurs
Callback Parameters
Property Type Description error String The error message
Code Example
Basic Error Handling
App ({
onLaunch () {
my . onError (( error ) => {
console . error ( 'JS Error:' , error );
});
}
});
Error Logging Service
App ({
onLaunch () {
my . onError (( error ) => {
// Log error to analytics service
this . logError ( error );
});
},
logError ( error ) {
my . request ({
url: 'https://api.example.com/errors' ,
method: 'POST' ,
data: {
error: error ,
timestamp: Date . now (),
appId: my . getAppIdSync (). appId
}
});
}
});
Page-Level Error Handling
Page ({
onShow () {
my . onError (( error ) => {
console . warn ( 'Error on page:' , error );
// Show user-friendly message
my . showToast ({
content: 'Something went wrong' ,
type: 'fail'
});
});
},
onHide () {
my . offError ();
}
});
Use Cases
App ({
onLaunch () {
my . onError (( error ) => {
// Send to monitoring service
this . sendToMonitoring ({
type: 'js_error' ,
message: error ,
page: getCurrentPages (). pop ()?. route ,
time: new Date (). toISOString ()
});
});
}
});
App ({
onLaunch () {
my . getRunScene ({
success : ({ envVersion }) => {
if ( envVersion === 'develop' ) {
my . onError (( error ) => {
// Show detailed error in development
my . alert ({
title: 'Debug Error' ,
content: error
});
});
}
}
});
}
});
App ({
onLaunch () {
my . onError (( error ) => {
// Attempt to recover from known errors
if ( error . includes ( 'network' )) {
my . showToast ({
content: 'Network error. Retrying...' ,
type: 'fail'
});
// Retry logic
}
});
}
});
The my.onError callback triggers at the same time as the onError() method in app registration, with the same parameters.
Currently, this API only captures JavaScript errors. Native errors and other types of exceptions may not be captured.
my.offError Stop listening for error events
my.onUnhandledRejection Listen for unhandled Promise rejections