0

How can I catch any exception that occurs in the client side code like "Pause On Caught Exceptions" on chrome developer tools?

Pedram
  • 828
  • 9
  • 24

3 Answers3

1

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 :)

Pedram
  • 828
  • 9
  • 24
0

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

TanguyP
  • 96
  • 1
  • 4
  • thanks for your reply,but i want to catch any exception in a function like window.onerror, even if I used the try catch blocks, without any modification in the application code! – Pedram Dec 05 '14 at 06:37
  • I'm not sure I understand what you want to achieve. You want to handle all your errors in a single function? Then haven't you answered your own question? Doesn't window.onerror suit your needs? – TanguyP Dec 05 '14 at 14:47
  • yes,you understand, but window.onerror not raised when we use the try/catch blocks in the code. – Pedram Dec 07 '14 at 21:33
  • I think that I found a solution to solve this problem,in the next post I will describe it. thanks for your reply ;) – Pedram Dec 07 '14 at 21:48
  • It's all a matter of propagating the exception or not. Take a look at the catch block in my answer above. If you do something in your catch block but don't propagate the exception using `throw`, you're saying you've fully handled the exception and nothing more needs to be done with it. If, however, you'd like the global error handler - or maybe another catch block somewhere in a calling method - to further handle your exception, you need to propagate the execption at the end of your catch block: `throw e;` (obviously, the name of the variable needs to reflect the name given in `catch(e)`) – TanguyP Dec 08 '14 at 09:59
0

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.

Suchit kumar
  • 11,809
  • 3
  • 22
  • 44
  • thanks for your reply,but i want to catch any exception in a function like window.onerror, even if I used the try catch blocks, without any modification in the application code! – Pedram Dec 05 '14 at 06:36