Catch all JavaScript client-side errors on the server-side

时光总嘲笑我的痴心妄想 提交于 2020-01-14 05:22:23

问题


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


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/27268691/catch-all-javascript-client-side-errors-on-the-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!