How can I catch any exception that occurs in the client side code like "Pause On Caught Exceptions" on chrome developer tools?
I found the solution!
I have used the C# and MVC.
Add a new class to customize your js files bundle like this:
public class CustomScriptBundle : ScriptBundle
{
public CustomScriptBundle(string virtualPath) : base(virtualPath)
{
Builder = new CustomScriptBundleBuilder();
}
public CustomScriptBundle(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath)
{
Builder = new CustomScriptBundleBuilder();
}
}
And, create another class to change the content of the js files as follows::
class CustomScriptBundleBuilder : IBundleBuilder
{
private string Read(BundleFile file)
{
//read file
FileInfo fileInfo = new FileInfo(HttpContext.Current.Server.MapPath(#file.IncludedVirtualPath));
using (var reader = fileInfo.OpenText())
{
return reader.ReadToEnd();
}
}
public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
{
var content = new StringBuilder();
foreach (var fileInfo in files)
{
var contents = new StringBuilder(Read(fileInfo));
//a regular expersion to get catch blocks
const string pattern = #"\bcatch\b(\s*)*\((?<errVariable>([^)])*)\)(\s*)*\{(?<blockContent>([^{}])*(\{([^}])*\})*([^}])*)\}";
var regex = new Regex(pattern);
var matches = regex.Matches(contents.ToString());
for (var i = matches.Count - 1; i >= 0; i--) //from end to start! (to avoid loss index)
{
var match = matches[i];
//catch( errVariable )
var errVariable = match.Groups["errVariable"].ToString();
//start index of catch block
var blockContentIndex = match.Groups["blockContent"].Index;
var hasContent = match.Groups["blockContent"].Length > 2;
contents.Insert(blockContentIndex,
string.Format("if(customErrorLogging)customErrorLogging({0}){1}", errVariable, hasContent ? ";" : ""));
}
var parser = new JSParser(contents.ToString());
var bundleValue = parser.Parse(parser.Settings).ToCode();
content.Append(bundleValue);
content.AppendLine(";");
}
return content.ToString();
}
}
Now, include your js files in application Bundles with your class:
BundleTable.Bundles.Add(new CustomScriptBundle("~/scripts/vendor").Include("~/scripts/any.js"));
Finally, in a new js file write customErrorLogging function as described below, and add it to your project's main html form:
"use strict";
var customErrorLogging = function (ex) {
//do something
};
window.onerror = function (message, file, line, col, error) {
customErrorLogging({
message: message,
file: file,
line: line,
col: col,
error: error
}, this);
return true;
};
Now, you can catch all exceptions in your application and manage them :)
You can use try/catch blocks:
try {
myUnsafeFunction(); // this may cause an error which we want to handle
}
catch (e) {
logMyErrors(e); // here the variable e holds information about the error; do any post-processing you wish with it
}
As the name indicates, you try to execute some code in the "try" block. If an error is thrown, you can perform specific tasks (such as, say, logging the error in a specific way) in the "catch" block.
Many more options are available: you can have multiple "catch" blocks depending on the type of error that was thrown, etc.
More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
see a small example how you can catch an Exception:
try {
alert("proper alert!");
aert("error this is not a function!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
<body>
<p id="demo"></p>
</body>
put you code in try Block and try to catch error in catch Block.
Related
And I wish the following objective:
assign an event to the hotmail calendar
I have the following code:
using Microsoft.Live;
private void editEvent()
{
try
{
var authClient = new LiveAuthClient();
LiveLoginResult result = await authClient.LoginAsync(new string[] { "wl.signin", "wl.calendars", "wl.calendars_update" });
if (result.Status == LiveConnectSessionStatus.Connected)
{
var eventToPost = new Dictionary<string, object>();
eventToPost.Add("name", "program my c# - 2nd trial");
eventToPost.Add("calendar_id", "calendar.136c10ca65544801.99c35f9a9fb341a3af35daa82f4569f8");
eventToPost.Add("description", "this should be 2nd calendar");
eventToPost.Add("start_time", "2019-09-10T01:30:00-08:00");
eventToPost.Add("end_time", "2019-09-12T03:00:00-08:00");
eventToPost.Add("location", "business placeeeeeee");
eventToPost.Add("is_all_day_event", false);
eventToPost.Add("availability", "busy");
eventToPost.Add("visibility", "public");
this.session = result.Session;
connected = true;
this.connectClient = new LiveConnectClient(result.Session);
var meResult = await connectClient.PutAsync("event.136c10ca6a355671.5f21a7994c7e40fd800bc48dcc07300b.991d1912ec6b4523a0f08839992aa2bb", eventToPost);
meData = meResult.Result;
}
}
catch (LiveAuthException ex)
{
// Display an error message.
}
catch (LiveConnectException ex)
{
// Display an error message.
infoTextBlock.Text += ex.Data + " ..." + ex.Message;
}
}
In which I try to test it to see how it works and if it fulfills the desired objective.
But I do not know which library works LiveAuthClient and LiveConnectSessionStatus
Download the nuget package live sdk package, but it still shows error in LiveAuthClient and LiveConnectSessionStatus
I would like to know which library should download to test its operation, since I want to add an event to the Hotmail calendar with C # or Javascript. If anyone knows, or if you have an example, I would greatly appreciate it.
I am working on a project at work and I am using CefSharp to connect c# to JS due to a restriction that I am not allowed to use external servers or even a localhost server to host php or other scripting language. The goal I need to reach is I have an async method in c# that works it is reading the csv that i need to accomplish my job, I have debug stepped through the values and its fine. it returns a Task In my js file which called the method to read the local file and return an array of strings to be handled. I get a pending promise, when i used await the pending promise sits there and halts my browser, I have been searching the internet for help and I havent found anything that seems to work. ill post as much of the current code as I can, I need to find a solution for this or atleast some good pointers to get the value from c# to resolve in the js script so that I can move forward.
//C# Code::
public Task<string[]> GetCSV()
{
return GetCSVAsync(Encoding.UTF8, pB.GetDefaultPath(PathSelection.AppPathWeb) + "\\MatId\\Includes\\misc\\questions.csv");
}
public async Task<string[]> GetCSVAsync(Encoding encoding, string path)
{
string[] lines = new string[1];
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, DefaultOptions))
{
using (StreamReader reader = new StreamReader(stream, encoding))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
lines = AddLineToLines(lines, line);
}
}
}
return lines;
}
/// <summary>
/// This code is opensourced.
/// </summary>
/// <param name="linesinarray">lines array</param>
/// <param name="linetoadd">line to add to the lines array</param>
/// <returns>lines array with new value in length</returns>
private string[] AddLineToLines(string[] linesinarray, string linetoadd)
{
if (String.IsNullOrWhiteSpace(linesinarray[0]))
{
linesinarray[0] = linetoadd;
return linesinarray;
}
else
{
string[] temp = new string[linesinarray.Length + 1];
for (int i = 0; i < linesinarray.Length; i++)
{
temp[i] = linesinarray[i];
}
temp[temp.Length - 1] = linetoadd;
return temp;
}
}
//JS Code::
//one attempt::
async function getCSVData() {
try {
var xValue = jsDBConnection.getCSV().then(function (res) {
console.log(res);
});
} catch (e) {
console.log(e.message);
}
}
//Attempt 2::
async function getCSVData() {
try {
var xValue = await jsDBConnection.getCSV();
return xValue;
} catch (e) {
console.log(e.message);
}
}
All of these call c# and run through the c# methods However on return the promise is pending statused and value is undefined, and then jquery runs in an infanite loop until either I pause execution or kill the process it never returns any value.
Im new to async programming and I feel that i can get it working but I dont know where I went wrong... I need some help and I am asking fto help me find what I did wrong.
Thank you,
Jesse Fender
I have these classes I want to add to my Parse Cloud Code:
function Rule = {
this.accessor = new Accessor();
this.act = new Action();
}
Rule.prototype.sendEmail = function(email, threshold, bill){
if (this.accessor.check(threshold, bill)){
this.act.actionTake(email, threshold, bill);
}
};
function Accessor = {
}
Accessor.prototype.check = function(threshold, bill){
return bill > threshold;
};
function Action = {
}
Action.prototype.actionTake = function(email, threshold, bill){
//send email code
};
but when I do add it to the very top of the javascript file
I get Update failed with Could not load triggers. The error was Uncaught SyntaxErrorL Unexpected token in main.js:1
Is Parse Cloud Code just for defining background jobs and cloud functions? Is it possible to add "class" definitions to Parse Cloud Code?
thank you
var Rule = function() {
this.accessor = new Accessor();
this.act = new Action();
};
or
function Rule() {
this.accessor = new Accessor();
this.act = new Action();
}
basic js syntax, nothing related to parse
anybody know how to access XML data using xpath expression in ECMA Script(datapower)?
IBM infocenter doesn't have this information on how to access XML data
Please provide if you have any sample script for accessing XML data
Thanks
GatewayScript doesn't support any XML Dom in the ECMA (Node.js) implemented.
I have however used the modules XPATH and DOM with great success.
Download XMLDom (https://github.com/jindw/xmldom) and Xpath (https://github.com/goto100/xpath) Node.js modules and add the following scripts to your DP directory:
dom-parser.js
dom.js
sax.js
xpath.js
To use it in DataPower GWS you first need to get the XML data from INPUT:
// This is where we start, grab the INPUT as a buffer
session.input.readAsBuffers(function(readAsBuffersError, data) {
if (readAsBuffersError) {
console.error('Error on readAsBuffers: ' + readAsBuffersError);
session.reject('Error on readAsBuffers: ' + readAsBuffersError);
} else {
if (data.slice(0,5).toString() === '<?xml') {
console.log('It is XML!');
parseXML(data);
}
} //end read as buffers error
}); //end read as buffer function
function parseXML(xml) {
// Load XML Dom and XPath modules
var select = require('local:///xpath.js');
var dom = require('local:///dom-parser.js');
var doc = new dom.DOMParser().parseFromString(xml.toString(), 'text/xml');
// Get attribute
var nodes = select(doc, "//root/element1/#protocol");
try {
var val = nodes[0].value.toString();
console.log('found xml attribute as ['+val+']');
} catch(e) {
// throw error here
}
// Get an element
nodes = select(doc, "//root/element1/child1");
try {
var val = nodes[0].firstChild.data;
console.log('elemnt found as ['+val+']');
} catch(e) {
//throw error here
}
}
That should be a working sample... You need to change the path for the modules if you move them.
I have a directory in store:/// where I add my GWS modules.
Hope you'll get it to fly!
At least from 7.0.0 firmware version Gatewayscript is able to work with XPATH and DOM easily. Snippet from the DP store:
//reading body from the rule input
session.input.readAsXML(function (error, nodeList) {
if (error) {
//error behaviour
} else {
var domTree;
try {
domTree = XML.parse(nodeList);
} catch (error) {
//error behaviour
}
var transform = require('transform'); //native gatewayscript module
transform.xpath('/someNode/anotherNode/text()', domTree, function(error, result){
if(error){
//error behaviour
}
//some use of result, for example putting it to output
session.output.write(result);
}
});
});
In my NodeJS program, I parse some user JSON file.
So I use :
this.config = JSON.parse(fs.readFileSync(path));
The problem is that if the json file is not correctly formated, the error thrown is like:
undefined:55
},
^
SyntaxError: Unexpected token }
at Object.parse (native)
at new MyApp (/path/to/docker/lib/node_modules/myApp/lib/my-app.js:30:28)
...
As it is not really user friendly I would like to throw an Error specifying some user friendly message (like "your config file is not well formated") but I want to keep the stacktrace in order to point to the problematic line.
In the Java world I used throw new Exception("My user friendly message", catchedException) in order to have the original exception which caused that one.
How is it possible in the JS world?
What I finally did is:
try {
this.config = JSON.parse(fs.readFileSync(path));
} catch(err) {
var newErr = new Error('Problem while reading the JSON file');
newErr.stack += '\nCaused by: '+err.stack;
throw newErr;
}
There is an new Error Cause proposal for ECMAScript, and it reached stage-4 at TC34!
It means it will be in the next ECMAScript version!
https://github.com/tc39/proposal-error-cause
You would provide the cause as an error option:
throw new Error(`Couldn't parse file at path ${filePath}`, { cause: err });
The ES proposal only formalize it on the language level, but browsers/NodeJS should normally agree to log the full causal chain in practice (see https://github.com/nodejs/node/issues/38725)
As of today (end of 2021), Firefox Devtools are already able to log nested stacktraces!
Joyent released a Node.js package that can be used exactly for that. It is called VError. I paste an example of how you would use the pacakge:
var fs = require('fs');
var filename = '/nonexistent';
fs.stat(filename, function (err1) {
var err2 = new VError(err1, 'stat "%s"', filename);
console.error(err2.message);
});
would print the following:
stat "/nonexistent": ENOENT, stat '/nonexistent'
2021 Update: To chain exceptions in JS:
class MyAppError extends Error {
constructor(...params) {
super(...params)
if (Error.captureStackTrace) {
// This is the key line!
Error.captureStackTrace(this, this.constructor);
}
this.name = this.constructor.name
}
}
See the Mozilla docs on Error.captureStackTrace
Use a try / catch block:
try {
this.config = JSON.parse("}}junkJSON}");
//...etc
}
catch (e) {
//console.log(e.message);//the original error message
e.message = "Your config file is not well formatted.";//replace with new custom message
console.error(e);//raise the exception in the console
//or re-throw it without catching
throw e;
}
http://jsfiddle.net/0ogf1jxs/5/
UPDATE: If you really feel the need for a custom error you can define your own:
function BadConfig(message) {
this.message = message;
this.name = "BadConfig";
}
BadConfig.prototype = new Error();
BadConfig.prototype.constructor = BadConfig;
try {
this.config = JSON.parse("}}badJson}");
} catch(e) {
throw new BadConfig("Your JSON is wack!");
}
http://jsfiddle.net/kL394boo/
Lots of useful info at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error