cocos2d-js 把JS错误打印到屏幕上

前端之家收集整理的这篇文章主要介绍了cocos2d-js 把JS错误打印到屏幕上前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在编程或者QA测试过程中,把debug的包中JS错误打印在屏幕上可以增加开发效率,降低定位bug时间成本。

修改ScriptingCore.cpp文件

void ScriptingCore::reportError(JSContext *cx,const char *message,JSErrorReport *report)
{
    js_log("%s:%u:%s\n",report->filename ? report->filename : "<no filename=\"filename\">",(unsigned int) report->lineno,message);

	// xiaohei add error layer
	ScriptingCore::getInstance()->showErrorLayer();
};

void ScriptingCore::showErrorLayer()
{
	int delv = 0;
	auto isDelv = localStorageGetItem("xh_error");
	if (!isDelv.empty()) {
		delv = atoi(isDelv.c_str());
	}

	if (_js_log_buf && delv > 0) {
		auto winSize = Director::getInstance()->getWinSize();
		auto errLayer = LayerColor::create();
		errLayer->initWithColor(Color4B(0,0),winSize.width,winSize.height);
		errLayer->setAnchorPoint(Point(0.5f,0.5f));
		errLayer->setPosition(Point(0,0));
		errLayer->setOpacity(200);
		Director::getInstance()->getRunningScene()->addChild(errLayer,10000000,952700);

		auto listener = EventListenerTouchOneByOne::create();
		listener->onTouchBegan = CC_CALLBACK_0(ScriptingCore::onErrorLayerTouchBegin,this);
		listener->setSwallowTouches(true);
		Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraPHPriority(listener,errLayer);

		std::string errlog = _js_log_buf;
		auto errorLabel = Label::createWithTTF(errlog,"common/font/DFGB_Y7_0.ttf",18);
		errorLabel->setColor(Color3B::WHITE);
		errorLabel->setAnchorPoint(Point(0.5f,0.5f));
		errorLabel->setPosition(Point(winSize.width / 2.0,winSize.height / 2.0 + 150));
		errLayer->addChild(errorLabel,10);

		std::string path = "res/ui/common/common_close.png";
		auto swapMenuItem = MenuItemImage::create(path,path,CC_CALLBACK_0(ScriptingCore::removeErrorLayer,this));
		auto swapMenu = Menu::createWithItem(swapMenuItem);
		swapMenu->setPosition(winSize.width - 100,winSize.height - 100);
		errLayer->addChild(swapMenu,100);
	}
}

bool ScriptingCore::onErrorLayerTouchBegin()
{
	return true;
}

void ScriptingCore::removeErrorLayer()
{
	Director::getInstance()->getRunningScene()->removeChildByTag(952700);
}
重写reportError把错误展示在屏幕上,并支持关闭操作 原文链接:https://www.f2er.com/cocos2dx/339267.html

猜你在找的Cocos2d-x相关文章