捕获服务器端的所有JavaScript客户端错误

问题描述 投票:0回答:3

如何捕获客户端代码中出现的任何异常,如Chrome开发人员工具上的“暂停捕获的异常”?

javascript c# asp.net-mvc error-handling single-page-application
3个回答
1
投票

我找到了解决方案!

我使用过C#和MVC。

添加一个新类来自定义您的js文件包,如下所示:

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();
    }
}

并且,创建另一个类来更改js文件的内容,如下所示::

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();
    }
}

现在,将您的js文件包含在您的类的应用程序包中:

BundleTable.Bundles.Add(new CustomScriptBundle("~/scripts/vendor").Include("~/scripts/any.js"));

最后,在一个新的js文件中编写如下所述的customErrorLogging函数,并将其添加到项目的主html表单中:

"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;
};

现在,您可以捕获应用程序中的所有异常并管理它们:)


0
投票

您可以使用try / catch块:

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
}

如名称所示,您尝试在“try”块中执行一些代码。如果抛出错误,您可以在“catch”块中执行特定任务(例如,以特定方式记录错误)。

还有更多选项可供使用:根据抛出的错误类型等,您可以拥有多个“catch”块。更多信息请访问:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch


0
投票

看一个小例子如何捕获异常:

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>

将代码放入try Block并尝试捕获catch Block中的错误。

© www.soinside.com 2019 - 2024. All rights reserved.