百度智能小程序 监听小程序错误事件

2020-09-04 16:28 更新

swan.onError

基础库 3.60.2 开始支持,低版本需做兼容处理。

解释: 监听小程序错误事件。如脚本错误或API调用报错等。该事件与 App.onError 的回调时机与参数一致。

方法参数

Function callback

小程序错误事件的回调函数。

callback 返回参数说明:

Object error

错误信息,包含堆栈。

示例



图片示例


代码示例 1:在生命周期的 onError 中使用 

在开发者工具中打开

// app.js
App({
    onError(err) {
        console.log('catch error', err);
        swan.showModal({
            content: JSON.stringify(err)
        });
    }
});

代码示例 2:等同于示例一的另一种写法 

在开发者工具中打开

// app.js
App({
    onLaunch() {
        swan.onError(function(errMsg) {
            console.log('catch error', errMsg);
            swan.showModal({
                content: JSON.stringify(errMsg)
            });
        });
    };
});

代码示例 3:可根据开发者的业务逻辑调整用法 

在开发者工具中打开

Page({
    onTap() {
        swan.showToast({
            title: '已触发',
            icon: 'none'
        });
        swan.onError(function(errMsg) {
            console.log('catch error', errMsg);
            swan.showModal({
                content: JSON.stringify(errMsg),
                complete: () => {
                    swan.offError();
                }
            })
        });
        throw new Error('这是一个页面报错'); // 报的错会被捕获到
    }
});


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号