php - 返回javascript代码时如何在PHP/Dojo中正确生成异常

标签 php javascript ajax exception dojo

当代码通过 AJAX 动态获取并通过 eval 执行时,我很难理解异常是如何处理的。 .使用客户端 javascript,这很简单,如果我有一段这样的代码

var j = 'some string';
j.propA.x++;

这将引发异常,因为 propA , 类型为 undefined没有 x .此外,引发的异常很容易理解。

现在让我们把上面的代码放在一个文本文件中,我们称之为 test.js ,并将其存储在服务器上。现在让我们用 Ajax 动态加载它。我正在使用以下代码动态加载它
dojo.xhrGet({
  url: 'load.php',
  handleAs: "javascript",
  content : {
    fileName : 'test.js'
  },
  load: function(returnValue) {
    /*Do Something*/
  },
  error: function(errorMessage) {
    /*Report Error*/
  }
});

这是一个非常基本的 php 脚本,用于加载文件并将其作为 javascript 代码返回
<?php
  $fileName = $_GET['fileName'];
  $handle = fopen($fileName , 'r');
  $script = fread($handle, filesize($fileName));
  fclose($handle);
  echo $script;
?>

在上面dojo.xhrGet打电话,error属性可以设置为一个函数来显示错误消息,这里是一些可以做到这一点的许多方法的例子。
error: function(errorMessage) {
  console.error(errorMessage);
  console.error(errorMessage.arguments);
  console.error(errorMessage.message);
  console.error(errorMessage.stack);
  console.error(errorMessage.type);
}

下面是一个输出示例。虽然这个输出是针对不同的问题,但它强调了它是多么难以理解:
Cannot read property 'x' of undefined
TypeError: Cannot read property 'x' of undefined
    at eval at <anonymous> (http://o.aolcdn.com/dojo/1.6/dojo/dojo.xd.js:14:3088)
    at Object.load (http://192.168.1.8/easel.js:166:6)
    at http://o.aolcdn.com/dojo/1.6/dojo/dojo.xd.js:14:89998
    at _144 (http://o.aolcdn.com/dojo/1.6/dojo/dojo.xd.js:14:36518)
    at _142 (http://o.aolcdn.com/dojo/1.6/dojo/dojo.xd.js:14:36328)
    at [object Object].<anonymous> (http://o.aolcdn.com/dojo/1.6/dojo/dojo.xd.js:14:36994)
    at _144 (http://o.aolcdn.com/dojo/1.6/dojo/dojo.xd.js:14:36780)
    at _142 (http://o.aolcdn.com/dojo/1.6/dojo/dojo.xd.js:14:36328)
    at [object Object].<anonymous> (http://o.aolcdn.com/dojo/1.6/dojo/dojo.xd.js:14:36994)
    at Object.resHandle (http://o.aolcdn.com/dojo/1.6/dojo/dojo.xd.js:14:92730)
non_object_property_load

我假设 dojo.xd.js:14eval 所在的行声明是。

如果人们知道他们在寻找什么,上述内容就足够了。但是,是否有更简单,或者至少更有效的方法来处理 eval 中出现的异常? ?

Here是一个有点类似的问题。

飞金提供了一个 good solution解决下面的这个问题,所以我给了他赏金。使用他的解决方案,我得到了一个看起来像这样的输出(我把它缩小了一点)
    ReferenceError in JS Code detected: (url: module.require.php?module=MainMenu.Bg_S)
easel.js:211Error Message: ReferenceError: apple is not defined
easel.js:213(function(){
return function(args){
dojo.require("Shape");

Module.assert('MainMenu_V');

/**
* The rectangular background of the Main View
* @property MainMenuBg_S
* @type Shape
**/
new Shape({
    /**
    * Unique descriptive name used when later accessing this shape via '$$()'
    * @param name
    * @type String
    **/
    name : 'MainMenu.Bg_S' , 
    /**
    * Left side of this rectangle
    * @param x
    * @type Number
    **/             
    x : $$('MainMenu_V').x , 

    /**
    * Top of this rectangle
    * @param y
    * @type Number
    **/ 
    y : $$('MainMenu_V').y , 

    /**
    * Width of this rectangle
    * @param w
    * @type Number
    **/ 
    w : $$('MainMenu_V').w , 

    /**
    * Height of this rectangle
    * @param h
    * @type Number
    **/ 
    h : $$('MainMenu_V').h , 

    /**
    * Type of this Shape
    * @param h
    * @type Number
    **/ 
    type : shapeType.RECTANGLE , 

    /**
    * Generate function which contains all the graphics instructions, as well as the contexts
    * to preload and initialize. This is currently under development. Backgrounds should NEVER
    * have mouse events associated with them as a redraw of a background implies a redraw of 
    * every single displayObject infront of the background.
    * @param generate
    * @type method
    **/   
    generate : function (){
        var x = this.x << 0 , y = this.y << 0 , h = this.h << 0 , w = this.w << 0 , a = this.a;

        this.graphics(contextID.LEAVE).lf([hsl(180,100,60,0.9),hsl(180,100,20,0.75)],[0,1],0,h/2,w,h/2).dr(x,y,w,h).ef();
        this.graphics(contextID.ENTER).lf([hsl(135,100,40,0.9),hsl(135,100,20,0.75)],[0,1],0,h/2,w,h/2).dr(x,y,w,h).ef();
        this.graphics(contextID.CLICK).lf([hsl(90,100,40,0.9),hsl(90,50,20,0.75)],[0,1],0,h/2,w,h/2).dr(x,y,w,h).ef();
        this.graphics(contextID.RCLICK).lf([hsl(90,110,40,0.9),hsl(80,60,20,0.45)],[0,1],0,h/2,w,h/2).dr(x,y,w,h).ef();
        this.graphics(contextID.DBLCLICK).lf([hsl(45,100,40,0.9),hsl(45,100,20,0.75)],[0,1],0,h/2,w,h/2).dr(x,y,w,h).ef();
        this.graphics(contextID.DBLRCLICK).lf([hsl(10,100,40,0.9),hsl(10,100,20,0.75)],[0,1],0,h/2,w,h/2).dr(x,y,w,h).ef();
        this.graphics(contextID.LPRESS).lf([hsl(110,25,40,0.9),hsl(110,25,20,0.75)],[0,1],0,h/2,w,h/2).dr(x,y,w,h).ef();
        this.graphics(contextID.RPRESS).lf([hsl(110,50,40,0.9),hsl(110,50,20,0.75)],[0,1],0,h/2,w,h/2).dr(x,y,w,h).ef();
        this.graphics(contextID.SCROLL).lf([hsl(110,50,40,0.9),hsl(110,50,20,0.75)],[0,1],0,h/2,w,h/2).dr(x,y,w,h).ef();

        if (debugFlags.BOUNDINGBOX()){
            this.graphics(contextID.ENTER).ss(2).s(rgba(0,255,0,a)).dr(this.boundingBox.softBounds.L +4<<0, this.boundingBox.softBounds.T +4<<0, this.boundingBox.softBounds.w-8<<0 , this.boundingBox.softBounds.h-8<<0).es();
            this.graphics(contextID.ENTER).ss(2).s(rgba(255,0,0,a)).dr(this.boundingBox.bounds.L +4<<0, this.boundingBox.bounds.T +4<<0, this.boundingBox.bounds.w-8<<0 , this.boundingBox.bounds.h-8<<0).es();
            this.graphics(contextID.ENTER).f(rgba(0,0,255,a)).dc(this.boundingBox.points[0].x+4 , this.boundingBox.points[0].y+4 , 4).ef();
            this.graphics(contextID.ENTER).f(rgba(0,0,255,a)).dc(this.boundingBox.points[1].x-8 , this.boundingBox.points[1].y+4 , 4).ef();
            this.graphics(contextID.ENTER).f(rgba(0,0,255,a)).dc(this.boundingBox.points[2].x-8 , this.boundingBox.points[2].y-8 , 4).ef();
            this.graphics(contextID.ENTER).f(rgba(0,0,255,a)).dc(this.boundingBox.points[3].x+4 , this.boundingBox.points[3].y-8 , 4).ef();
        }
    },

    /**
    * Arguments to pass to the mouse initialization function. These will get mixed in (via
    * dojo.mixin) to the mouse object. To increase performance, the signalOrderIn has been set to
    * NOHIT. This will limit the number of redraws (remember background redraws are extremely
    * expensive as they require redrawing everything in the container). The signalOrderOut is 
    * then set to BLOCK to prvent anything behind the background from receiving mouse signals
    * (this is actually unecessary as the only think behind the background is, and always should
    * be, the container, which itself has signalOrderIn and signalOrderOut set to NOHIT and BLOCK
    * respectively).
    * @param mouse
    * @type Object
    **/ 
    mouse : {
        _signalOrderIN : signalFlags.NOHIT ,
        _signalOrderOUT : signalFlags.BLOCK
    } ,

    /** 
    * All views are initially loaded via Ajax. Generally, views do not have any preconditions, beyond
    * that the stage be present. They can, however, and generally do, have modules they require. These
    * are called after this view has been created and loaded (load() function call). They are called
    * in the order of the sub arrays. In the example below:
    * [[A , B , C , D , E , F , G]]
    * The 7 modules are requested in that order, but, due to Ajax, they can be loaded in any order. 
    * In the below example, on the other hand:
    * [[A] , [B , C , D , E , F , G]]
    * Modules B-G depend on module A, therefore, module A is ordered to be loaded first. 
    * @property providedModules
    * @type Array[Array[String]]
    * @protected
    **/
    providedModules : [[]] ,

    /** 
    * Carries out all the initializations when loading the module
    * @method load
    * @protected
    **/
    load : function (){
                0/apple;
        $$('MainMenu_V').addChild(this);
    } ,

    /** 
    * Carries out all memory deallocation when leaving the module (generally only necessary if modules
    * were loaded but not added to stage as in the case with cached bitmaps)
    * @method leave
    * @protected
    **/
    leave : function (){
    }
});
$$('MainMenu.Bg_S')._code="dojo.require(\"Shape\");...";
};
}());

easel.js:217Error triggered by: function (_2bd){return err.call(args,_2bd,_2b7);}
easel.js:220XHR Object:
easel.js:221
Object
args: Object
handleAs: "javascript"
query: null
url: "module.require.php?module=MainMenu.Bg_S"
xhr: XMLHttpRequest
__proto__: Object
easel.js:222Error Object:
easel.js:223
ReferenceError
arguments: Array[1]
message: "—"
stack: "—"
type: "not_defined"
__proto__: Error
dojo.xd.js:14
ReferenceError
arguments: Array[1]
message: "—"
stack: "—"
type: "not_defined"
__proto__: Error
dojo.xd.js:14
ReferenceError
arguments: Array[1]
message: "—"
stack: "—"
type: "not_defined"
__proto__: Error

我需要的唯一缺少的是能够指出问题发生在哪一行。

最佳答案

这是一个从 xhr-get 请求中检测与网络无关的错误并在控制台中输出有关它的一些信息的片段。

有一个额外的 isEvalError() 函数可以处理所有 eval-error 类型......我并不为此感到自豪。更好的方法是获取 errorMessage 子类的父对象。
我认为您通常可以放弃 isEvalError() ,因为此块中不应该有任何其他错误。

function isEvalError(errorMessage){
    return errorMessage.name == "RangeError" ||
    errorMessage.name == "ReferenceError" ||
    errorMessage.name == "SyntaxError" ||
    errorMessage.name == "URIError" ||
    errorMessage.name == "TypeError";
}

var foo = dojo.xhrGet({
    url: 'stacko.js',
    handleAs: "javascript",
    load: function(returnValue) {
        console.log("load: "+returnValue);
    },
    error: function(errorMessage,ioargs) {

        //request worked fine, this must be a non-network related error
        if(ioargs.xhr.readyState == 4 && ioargs.xhr.status == 200) {


            if(isEvalError(errorMessage)){
                //show eval-error, url request & the JS code that causes the exception
                //eval-error types: RangeError,ReferenceError,SyntaxError, URIError, TypeError
                console.error(errorMessage.name+" in JS Code detected: (url: "+ioargs.url+")")
                console.error("Error Message: "+ errorMessage);

                console.error(ioargs.xhr.responseText);
            }

            //a little reflection - if u want to know who triggered this error 
            //(although in this case the output is not very helpful )
            console.error("Error triggered by: "+arguments.callee.caller.toString());

            //last but not least log the error & the xhr-request object for more information
            console.error("XHR Object:");
            console.error(ioargs);
            console.error("Error Object:");
            console.error(errorMessage);


        }


    }
});

关于php - 返回javascript代码时如何在PHP/Dojo中正确生成异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7265371/

相关文章:

php - 覆盖所有串联组合的简单方法

php - MYSQL和PHP:没有结果的SELECT子查询返回空值的数组键

javascript - ( Node :9263) UnhandledPromiseRejectionWarning: ValidationError: ideas validation failed: imageUrl: Path `imageUrl` is required

javascript - jQuery插入元素并覆盖

javascript - 鼠标悬停在div元素内的链接不起作用

javascript - 无法使用api调用的json响应填充html表

javascript - 长时间运行的 AJAX 请求在几分钟后重新提交

javascript - 基于表单输入值,如何 2 生成选择 4 从数据库中生成带有行/记录数据的下拉菜单,该数据库将在选择时预填充表单?

php - 使用 phpexcel 从 mysql 数据库创建 excel 报告

php - 如何连续运行 PHP 脚本?