Drupal 8.7.8 Custome Module Created Rest Resource (API) not found - php

Directory structure:
module_name -> config -> install -> rest.resource.location_api.yml
id: location_api
plugin_id: location_api
granularity: resource
configuration:
methods:
- GET
- POST
- PATCH
- DELETE
formats:
- json
authentication:
- cookie
module_name/src/plugin/rest/resource/LocationApi.php
<?php
namespace Drupal\locations\Plugin\rest\resource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\Core\Controller\ControllerBase;
//use Drupal\node\Entity\Node;
//use Drupal\taxonomy\Entity\Term;
use Drupal\user\Entity\User;
//use Drupal\Core\Database\Connection;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* Provides a KDR's Rest Custom Resource For Locations
*
* #RestResource(
* id = "location_api",
* label = #Translation("KDR's Rest Custom Resource For Location"),
* uri_paths = {
* "canonical" = "/kdr-apis/v1.0/location/{sl_id}",
* "https://www.drupal.org/link-relations/create" = "/kdr-apis/v1.0/location"
* }
* )
*/
class LocationApi extends ResourceBase {
}
but when I install the module, then it returns an error,
Message
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "entity_bundle:node" plugin does not exist. Valid plugin IDs for Drupal\Core\Condition\ConditionManager are: node_type, request_path, current_theme, user_role in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 53 of /home/linuxdem/kdr.linuxdemos.me/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

This was the Drupal 8 cache issue, I have resolved by clearing cache and re-installing module.

Related

How to set #SWG\Info annotation for only area in Symfony using NelmioApiDocBundle

/**
* #SWG\Swagger(
* #SWG\Info(
* title="My first swagger documented API",
* version="1.0.0"
* )
* )
*/
I tried to write this block in:
my base controller - src/MyProject/ApiBundle/Controller/SiteApi/SiteApiBaseController.php
my bundle file - src/MyProject/ApiBundle/MyProjectApiBundle.php
Generated JSON contains empty "info": {"title": ""}
Symfony 3.4, NelmioApiDocBundle 3.9.1(including zircote/swagger-php 2.0.9)
• For controller try:
/**
use FOS\RestBundle\Controller\Annotations as Rest;
use Swagger\Annotations as SWG;
...
* Add Tva.
* #Rest\Post("/tva/add")
* #SWG\Tag(name="TVA Management")
...
...
* #SWG\Response(response=201, description="Tva created successfully.")
...
...
*/
=> You will get something like this:
• For api/doc page Title, Description & Version, try to edit this file:
~Your_Project_Path\config\packages\nelmio_api_doc.yaml

Azure PHP SDK: get the asset by asset name

Is it possible to get the asset details using asset name with Azure PHP sdk. I can get all the asset list, but it's loading first 1000 assets only.
getAssetList();
I can get single asset details using asset id.
getAsset($asset);
But in my case, I don't have asset id with me. I just have asset name alone. Now how do I get the asset details using this?
EDIT:
I got some help from Azure support saying that, we can use $skip parameter for pagination. I got code snippet in c#
for (int i = 0; i < _context.Assets.Count(); i += 1000 )
{
var assets = _context.Assets.Skip(i);
foreach (IAsset objIAsset in assets)
{
Console.WriteLine(objIAsset.Name.ToString());
}
}
How can I use this param in PHP SDK.
It seem that Azure SDK for PHP don't support skip method. However, I used the fiddler to monitor C# skip method and got the URL like this:
https://***-hs.cloudapp.net/api/Assets()?$skip=1000
So I think we can bulid up the request path like above in our PHP project and we can modify the getAssetList method in "MediaServicesRestProxy" file.
I add a function named "getAssetListBySkip($number)" into "MediaServicesRestProxy" class, the code like this:
/**
* Get asset list using skip number
*
* */
public function getAssetListBySkip($number)
{
$propertyList = $this->_getEntityList("Assets()?".'$skip='.$number);
$result = array();
foreach ($propertyList as $properties) {
$result[] = Asset::createFromOptions($properties);
}
return $result;
}
We can call this method like this:
$mediaServiceProxy = ServicesBuilder::getInstance()->createMediaServicesService(
new MediaServicesSettings("**","**/**="));
$result=$mediaServiceProxy->getAssetListBySkip(1000);
Azure Media services supports filtering by name. You can construct web request to be like
/api/assets()?$filter=Name%20eq%20'Your Name'&$top=1
You can also filter by other properties
Have you tried REST API that are used when creating, processing, managing, and delivering Assets. https://msdn.microsoft.com/en-us/library/azure/hh974277.aspx#list_an_asset but I do think we can list asset via a name directly since id is an unique indentifier of asset entity. PHP Azure SDK leverages assetId to get an Asset as well:
public function getAsset($asset)
{
$assetId = Utilities::getEntityId(
$asset,
'WindowsAzure\MediaServices\Models\Asset'
);
return Asset::createFromOptions($this->_getEntity("Assets('{$assetId}')"));
}
But in my case, I don't have asset id with me. I just have asset name
alone. Now how do I get the asset details using this?
Here are some test function code snippets for your reference:
public function testListAllAssets(){
// Setup
$asset1 = new Asset(Asset::OPTIONS_NONE);
$asset1->setName(TestResources::MEDIA_SERVICES_ASSET_NAME . $this->createSuffix());
$asset2 = new Asset(Asset::OPTIONS_NONE);
$asset2->setName(TestResources::MEDIA_SERVICES_ASSET_NAME . $this->createSuffix());
// Test
$asset1 = $this->createAsset($asset1);
$asset2 = $this->createAsset($asset2);
$result = $this->restProxy->getAssetList();
// Assert
$this->assertCount(2, $result);
$names = array(
$result[0]->getName(),
$result[1]->getName()
);
$id = array(
$result[0]->getId(),
$result[1]->getId()
);
$this->assertContains($asset1->getName(), $names);
$this->assertContains($asset2->getName(), $names);
$this->assertContains($asset1->getId(), $id);
$this->assertContains($asset2->getId(), $id);
}
public function testGetAnAssetReference(){
// Setup
$assetName = TestResources::MEDIA_SERVICES_ASSET_NAME . $this->createSuffix();
$asset = new Asset(Asset::OPTIONS_NONE);
$asset->setName($assetName);
$asset = $this->createAsset($asset);
// Test
$result = $this->restProxy->getAsset($asset);
// Assert
$this->assertEquals($asset->getId(), $result->getId());
$this->assertEquals($asset->getName(), $result->getName());
}
From: https://github.com/Azure/azure-sdk-for-php/blob/master/tests/functional/WindowsAzure/MediaServices/MediaServicesFunctionalTest.php
According to my testing, it seems that we can’t use Asset’s name to get the information of asset in Media Service.
$mediaServiceProxy = ServicesBuilder::getInstance()->createMediaServicesService(
new MediaServicesSettings("**","******"));
$asset = new Asset(Asset::OPTIONS_NONE);
$asset->setName('For-Test-wmv-Source');
//$asset don't have the value of id,
// unless execute ‘createAsset($asset)’, "$asset1" will be set the ID
$asset1 =$mediaServiceProxy->createAsset($asset);
$result2=$mediaServiceProxy->getAsset($asset1);
PHP SDK support the method named “getAsset($asset)”. Actually, the method get the Asset information by Asset id, just like the Aka's reference code.And Azure REST API don’t support the method queried by Asset’s name.
Please refer to the official document.
Alternative approach is that you can store your assets information (such as Id,URl,name and ect.) into Azure table storage when you upload them into media service. If you want to use it, you can fetch and filter the data of Asset’s name you wants from table storage.

Symfony routing - locale as subdomain with fallback to default

I'm trying to set up routing system with subdomain representing current locale. Routing is set via #Routing annotation and looks like this:
/**
* #Route(
* "/",
* name="homepage",
* host="{locale}.{domain}",
* defaults={"locale" = "en", "domain" = "%domain%"},
* requirements={"locale" = "en|de|fr", "domain" = "%domain%"}
* )
*/
Works well for URL's like en.somedomain.com or de.somedomain.com, but fails to find correct route for somedomain.com, without locale.
I understand that because of the host parameter, that is set to represent exact locale.domain pattern, but I can't find way to tell Symfony routing system that there could be additional, default host.
Searched all around for this, but found nothing particular. Would appreciate any help!
UPDATE
There is actually a way to do it, by adding another #Route in annotation, without host parameter:
/**
* #Route(
* "/",
* name="homepage_default",
* defaults={"locale" = "en"}
* )
*/
but thats looks a bit dirty, and I'm not using %domain% parameter there, which is important for me - say, if I would need another subdomain for mobile version.
Well, looks like triple annotation routing to handle locale + subdomain is the only choice for now.
Studying documentation (for example, this article) shows that Symfony developers encourage us to do it that way, which, to me, is not that nice. However, here's the solution...
/**
* #Method({"GET"})
* #Route(
* "/",
* name="homepage",
* host="{mobile}.{_locale}.{domain}",
* defaults={"mobile" = "moblie", "locale" = "%locale%", "domain" = "%domain%"},
* requirements={"mobile" = "mobile|m", "_locale" = "%locale%|de|fr", "domain" = "%domain%"}
* )
* #Route(
* "/",
* name="homepage",
* host="{_locale}.{domain}",
* defaults={"_locale" = "%locale%", "domain" = "%domain%"},
* requirements={"_locale" = "%locale%|de|fr", "domain" = "%domain%"}
* )
* #Route(
* "/",
* name="homepage_default",
* defaults={"_locale" = "%locale%"}
* )
*/
Notice that order is important, starting from subdomains, going down to default. As this looks ugly with #Route annotation, I've decided to re-write this in YAML as well:
homepage_locale_mobile:
path: /
host: "{mobile}.{_locale}.{domain}"
defaults: { mobile: "mobile", _locale: "%locale%", domain: "%domain%" }
requirements:
mobile: "mobile|m"
_locale: "%locale%|de|fr",
domain: "%domain%"
homepage_locale:
path: /
host: "{_locale}.{domain}"
defaults: { _locale: "%locale%", domain: "%domain%" }
requirements:
_locale: "%locale%|de|fr",
domain: "%domain%"
homepage:
path: /
defaults: { _locale: "%locale%" }
Ordered as well. Maybe someone will come across and use it.
I've just had a similar problem with defaults, though it was a route parameter and not locale.
The solution was there to replace the = signs with : as it should be that and the compiler somehow doesn't complains about it.
So try this one out:
/**
* #Route(
* "/",
* name="homepage",
* host="{locale}.{domain}",
* defaults={"locale" : "en", "domain" : "%domain%"},
* requirements={"locale" : "en|de|fr", "domain" : "%domain%"}
* )
*/

PHP Swagger and Yii

I have searched and found i have been lost all day now, and I feel I am going round in circles.
I have written, (with help of a few guides), a simple API for my Yii based application.
I have now come to document this API for other to use it.
I read everywhere that Swagger seems to be the way to go to implement, API documentation.
However I can seem to get anywhere on how to use this application
I have followed the instructions on Swagger PHP
Now I am lost has anyone got any examples of what to do next.
I have tried doing some self annotations of my ApiController.php and this doesnt work. I have been trying using the swagger.phar command line, but I still get no where.
I know you will need a lot more information but i dont know what bits of info you need so rather than pasting lots of useless information please ask and i will send anything you need.
To be honest all i would like is some simple API documentation but it just seems impossible.
Cheers
I have implemented swagger-php in my project. Please follow the below suggested instructions :
1) Download swagger-php(github.com/zircote/swagger-php) and swagger-ui(github.com/wordnik/swagger-ui). Extract them to your workspace.
2) Create a folder called swagger-api and blank php file called index.php in you workspace and paste the following code.
<?php
use Swagger\Annotations as SWG;
/**
* #SWG\Resource(
* apiVersion="0.2",
* swaggerVersion="1.2",
* resourcePath="/api.php",
* basePath="http://localhost/swagger-api/"
* )
*/
// Run this in url
// localhost/index.php?action=get_app_list
// This is the API,show the list in array
/**
*
* #SWG\Api(
* path="/api.php?action=get_app_list",
* description="Operations about get app list",
* produces="['application/json']",
* #SWG\Operations(
* #SWG\Operation(
* method="GET",
* summary="Find facet by ID",
* notes="Returns a facet based on ID",
* type="ListResult",
* nickname="getAllResults",
* #SWG\ResponseMessages(
* #SWG\ResponseMessage(
* code=400,
* message="Invalid ID supplied"
* ),
* #SWG\ResponseMessage(
* code=404,
* message="facet not found"
* )
* )
* )
* )
* )
*/
function get_app_list()
{
//normally this info would be pulled from a database.
//build JSON array
$app_list = array(array("id" => 1, "name" => "Web Demo"),
array("id" => 2, "name" => "Audio Countdown"),
array("id" => 3, "name" => "The Tab Key"), array("id" => 4,
"name" => "Music Sleep Timer"));
return $app_list;
}
$possible_url = array("get_app_list");
$value = "An error has occurred";
if (isset($_GET["action"]) && in_array($_GET["action"], $possible_url))
{
switch ($_GET["action"])
{
case "get_app_list":
$value = get_app_list();
break;
$value = "Missing argument";
break;
}
}
//return JSON array
echo(json_encode($value));
?>
3) Create a folder named swagger-docs in workspace.
4) Open you terminal and go the location of swagger-php in you workspace(i.e cd workpace/swagger-php).
5) Execute the following in your terminal
php swagger.phar /workspace/swagger-api -o /workspace/swagger-docs (This can be executed where we contain swagger.phar file).
6) You will see some files created on your swagger docs folder.
7) Open index.html in swagger-ui/dist/
8) Replace -: url: "http://petstore.swagger.wordnik.com/api/api-docs" to url: "http:localhost/swagger-docs"
9) Run localhost/swagger-ui/dist in your browser.

How to properly generate exceptions in PHP/Dojo when returning javascript code

I am having difficulty understanding how exceptions are handled when code is fetched dynamically via AJAX and executed via eval. With clientside javascript, it is rather simple, if I have a piece of code such as this
var j = 'some string';
j.propA.x++;
this will raise an exception because propA, which is of type undefined does not have an x. Furthermore, the exception raised is very easy to understand.
Now lets put the above code in a text file, lets call it test.js, and store it on the server. Now lets load it dynamically with Ajax. I am using the following code to load it dynamically
dojo.xhrGet({
url: 'load.php',
handleAs: "javascript",
content : {
fileName : 'test.js'
},
load: function(returnValue) {
/*Do Something*/
},
error: function(errorMessage) {
/*Report Error*/
}
});
Here is a very basic php script for loading the file and returning it as javascript code
<?php
$fileName = $_GET['fileName'];
$handle = fopen($fileName , 'r');
$script = fread($handle, filesize($fileName));
fclose($handle);
echo $script;
?>
In the above dojo.xhrGet call, the error property can be set to a function to display the error message, here is an example of some of the many ways this can be done.
error: function(errorMessage) {
console.error(errorMessage);
console.error(errorMessage.arguments);
console.error(errorMessage.message);
console.error(errorMessage.stack);
console.error(errorMessage.type);
}
Below is an example of the output. Although this output is for a different problem, it highlights how incomprehensible it is:
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
I am assuming dojo.xd.js:14 is the line where the eval statement is.
If one knows what they are looking for, the above might suffice. However, is there an easier, or at least a more productive way to deal with exceptions arising in eval?
Here is a somewhat similar question.
Phikin provided a good solution to this problem below so I gave him the bounty. Using his solution, I got an output which looked something like this (I cut it down a bit)
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
The only thing it's missing, that I need, is the ability to indicate what line the problem occurred.
Here is a snipped that detectes non-network related errors from an xhr-get request and outputs some information about it in the console.
There is an extra isEvalError() function that goes through all eval-error types... which I am not really proud of. A nicer way could be by getting the parent object of the errorMessage sub-classes.
I think you can ditch isEvalError() generally, because there shouldn´t be any other error possible in this block.
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);
}
}
});
It really depends on what you mean "productive way to deal with exceptions". If all you need to do is view the exception contents, a simple
console.log(errorMessage);
will allow you to effortlessly inspect the error object in decent browser like Chrome or Firefox (with Firebug). (Instead of forcing you to do a ton of console.log statements)
An annoying thing about Dojo exceptions inside asynchronous code is that they are always caught and handled so most browser debuggers ignore them. A notable exception to this rule is Chrome, where you can tell the debugger to pause on all exceptions.
BTW: I don't see how Javascript exceptions and Dojo have anything to do with PHP in this case, since they occur on the client side and there is nothing the server can do about them. Also, what the hell are you doing by sending Javascript code in the AJAX? Most of the time a client does a request it will be for data, in plain text, JSON or XML.

Categories