乐趣区

关于小程序:校友小程序开发笔记十二-小程序异常监控及错误处理

在小程序中应用抛出异样机制能让代码构造更加的简洁,缩小很多的逻辑判断,并且可能失去出错时的具体错误信息,可说是好处多多,明天

要说的就是在校友录小程序的 js 中抛出(throw)异样。js 中能够抛出任何类型的异样,比方数字、字符串甚至布尔值,例如:

<script>
    try {
        throw 'error';
        throw 123;
        throw false;
    }
    catch (e) {alert(e);
    }
</script>

当然,像大多数的面向对象语言中有内置的 Exception 类一样,js 中也有内置的异样类:Error,

/**
 * Notes: 利用异样解决类 
 * Date: 2020-09-05 04:00:00
 * Version : CCMiniCloud Framework Ver 2.0.1  


const appCode = require('./app_code.js');

class AppError extends Error {constructor(message, code = appCode.LOGIC) {super(message);  
      this.name = 'AppError';  
      this.code = code;
    }
  }

  module.exports = AppError;

咱们能够自定义异样类并继承 Error 基类:

错误代码定义:

 
/**
 * Notes: 错误代码定义
 * Ver : CCMiniCloud Framework 2.0.1 
 * Date: 2020-09-05 04:00:00
 * Version : CCMiniCloud Framework Ver 2.0.1  
 */
module.exports = {
    SUCC: 200,
    SVR: 500, // 服务器谬误  
    LOGIC: 1600, // 逻辑谬误 
    DATA: 1301, // 数据校验谬误 
    HEADER: 1302, // header 校验谬误  
    NOT_USER: 1303, // 用户不存在
    USER_EXCEPTION: 1304, // 用户异样 
    MUST_LOGIN: 1305, // 须要登录 
    USER_CHECK: 1306, // 用户审核中
    
    ADMIN_ERROR: 2001 // 管理员谬误
}
 
 

在校友录小程序中利用:

    // 获得 openid
    const cloud = cloudBase.getCloud();
    const wxContext = cloud.getWXContext();
    let r = '';

    try {if (!util.isDefined(event.router)) {console.error('Router Not Defined');
            return handlerSvrErr();}

        r = event.router.toLowerCase();

        // 路由不存在
        if (!util.isDefined(router[r])) {console.error('Router [' + r + '] Is Not Exist');
            return handlerSvrErr();}

        let routerArr = router[r].split('@');

        let controllerName = routerArr[0];
        let actionName = routerArr[1];
        let token = event.token || '';
        let params = event.params;

        console.log('');
        console.log('');
        let time = timeUtil.time('Y-M-D h:m:s');
        console.log('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++');
        console.log('[' + time + '][Request][Route=' + r + '], Controller=[' + controllerName + '], Action=[' + actionName + '], Token=[' + token + '], ###IN DATA=\r\n', JSON.stringify(params, null, 4));


        let openId = wxContext.OPENID;

        if (!openId) {console.error('OPENID is unfined');
            if (config.TEST_MODE)
                openId = config.TEST_TOKEN_ID;
            else
                return handlerSvrErr();}

        // 引入逻辑 controller
        controllerName = controllerName.toLowerCase().replace('controller', '').trim();
        const ControllerClass = require('controller/' + controllerName + '_controller.js');
        const controller = new ControllerClass(openId, params, r, token);

        // 调用办法    
        let result = await controller[actionName]();

        // 返回值解决
        if (!result)
            result = handlerSucc(r); // 无数据返回
        else
            result = handlerData(result, r); // 有数据返回

        console.log('------');
        time = timeUtil.time('Y-M-D h:m:s');
        console.log('[' + time + '][Response][Route=' + r + '], ###OUT DATA=', result);
        console.log('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++');
        console.log('');
        console.log('');

        return result;


    } catch (ex) {const log = cloud.logger();

        if (ex.name == 'AppError') {
            log.warn({
                router: r,
                errCode: ex.code,
                errMsg: ex.message
            });
            // 自定义 error 解决
            return handlerAppErr(ex.message, ex.code);
        } else {console.log(ex);
            log.error({
                router: r,
                errCode: ex.code,
                errMsg: ex.message,
                errStack: ex.stack
            });

            // 零碎 error
            return handlerSvrErr();}
    }
退出移动版