当前位置: 首页> 教育> 高考 > creator-错误捕获

creator-错误捕获

时间:2025/7/13 14:22:08来源:https://blog.csdn.net/yangxuan0261/article/details/141634413 浏览次数:0次

title: creator-错误捕获
categories: Cocos2dx
tags: [creator, 优化]
date: 2024-08-26 11:55:01
comments: false
mathjax: true
toc: true

creator-错误捕获


前篇

遇到 exception 和未知的错误时, 需要捕获, 方便上线后排除问题.


web 平台

  • 提供了监听函数

    window.onunhandledrejection = (event: PromiseRejectionEvent) => {console.error('--- onunhandledrejection message:', event.reason.message)console.error('--- onunhandledrejection stack:', event.reason.stack)
    }
    window.onerror = function (errMsg: string, file: string, lineNo: number, columnNo: number, errObj: Error, ...args) {console.error('--- onunhandledrejection errMsg:', errMsg)console.error('--- onunhandledrejection file:', file)console.error('--- onunhandledrejection lineNo:', lineNo)console.error('--- onunhandledrejection columnNo:', columnNo)console.error('--- onunhandledrejection errObj:', errObj)console.error('--- onunhandledrejection args:', args)
    }
    

原生平台

cocos 模式是可以通过 window['__errorHandler'] 捕获错误, 但是 promise 的错误捕获不到

  1. 修改 CocosApplication.cpp 文件, 把错误传给 js

    如: d:/CocosEditor/Creator/3.8.3/resources/resources/3d/engine/native/cocos/application/CocosApplication.cpp, 里面就是抛出了一个 CC_LOG_ERROR

    #include "cocos/bindings/jswrapper/SeApi.h" // 引入脚本 apivoid CocosApplication::handleException(const char *location, const char *message, const char *stack) {// Send exception information to server like Tencent Bugly.// 尝试获取 window.gMyErrHandler, 有的话把报错信息传过去, 没有还是默认的 CC_LOG_ERRORse::ScriptEngine* engine = se::ScriptEngine::getInstance();se::AutoHandleScope hs;se::Value globalVal;if (engine->getGlobalObject()->getProperty("window", &globalVal)) {se::Object* globalObj = globalVal.toObject();se::Value funcVal;if (globalObj->getProperty("gMyErrHandler", &funcVal) && funcVal.isObject() && funcVal.toObject()->isFunction()) {se::Object* funcObj = funcVal.toObject();se::ValueArray args;args.push_back(se::Value(location));args.push_back(se::Value(message));args.push_back(se::Value(stack));funcObj->call(args, globalObj);} else {CC_LOG_ERROR("\nUncaught Exception:\n - location :  %s\n - msg : %s\n - detail : \n      %s\n", location, message, stack);}} else {CC_LOG_ERROR("\nUncaught Exception:\n - location :  %s\n - msg : %s\n - detail : \n      %s\n", location, message, stack);}
    }
    
  2. js 中注册一个 gMyErrHandler 处理函数

    if (Tool.IsMobile()) {window.gMyErrHandler = function (location, msg, stack) {...}
    } 
    

关键字:creator-错误捕获

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: