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

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

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

修改ScriptingCore.cpp文件

  1. void ScriptingCore::reportError(JSContext *cx,const char *message,JSErrorReport *report)
  2. {
  3. js_log("%s:%u:%s\n",report->filename ? report->filename : "<no filename=\"filename\">",(unsigned int) report->lineno,message);
  4.  
  5. // xiaohei add error layer
  6. ScriptingCore::getInstance()->showErrorLayer();
  7. };
  8.  
  9. void ScriptingCore::showErrorLayer()
  10. {
  11. int delv = 0;
  12. auto isDelv = localStorageGetItem("xh_error");
  13. if (!isDelv.empty()) {
  14. delv = atoi(isDelv.c_str());
  15. }
  16.  
  17. if (_js_log_buf && delv > 0) {
  18. auto winSize = Director::getInstance()->getWinSize();
  19. auto errLayer = LayerColor::create();
  20. errLayer->initWithColor(Color4B(0,0),winSize.width,winSize.height);
  21. errLayer->setAnchorPoint(Point(0.5f,0.5f));
  22. errLayer->setPosition(Point(0,0));
  23. errLayer->setOpacity(200);
  24. Director::getInstance()->getRunningScene()->addChild(errLayer,10000000,952700);
  25.  
  26. auto listener = EventListenerTouchOneByOne::create();
  27. listener->onTouchBegan = CC_CALLBACK_0(ScriptingCore::onErrorLayerTouchBegin,this);
  28. listener->setSwallowTouches(true);
  29. Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraPHPriority(listener,errLayer);
  30.  
  31. std::string errlog = _js_log_buf;
  32. auto errorLabel = Label::createWithTTF(errlog,"common/font/DFGB_Y7_0.ttf",18);
  33. errorLabel->setColor(Color3B::WHITE);
  34. errorLabel->setAnchorPoint(Point(0.5f,0.5f));
  35. errorLabel->setPosition(Point(winSize.width / 2.0,winSize.height / 2.0 + 150));
  36. errLayer->addChild(errorLabel,10);
  37.  
  38. std::string path = "res/ui/common/common_close.png";
  39. auto swapMenuItem = MenuItemImage::create(path,path,CC_CALLBACK_0(ScriptingCore::removeErrorLayer,this));
  40. auto swapMenu = Menu::createWithItem(swapMenuItem);
  41. swapMenu->setPosition(winSize.width - 100,winSize.height - 100);
  42. errLayer->addChild(swapMenu,100);
  43. }
  44. }
  45.  
  46. bool ScriptingCore::onErrorLayerTouchBegin()
  47. {
  48. return true;
  49. }
  50.  
  51. void ScriptingCore::removeErrorLayer()
  52. {
  53. Director::getInstance()->getRunningScene()->removeChildByTag(952700);
  54. }
重写reportError把错误展示在屏幕上,并支持关闭操作

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