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

时间:2014-12-03 10:03:23

标签: javascript c# asp.net-mvc error-handling single-page-application

我如何捕获客户端代码中发生的任何异常,例如"暂停捕获的异常"在chrome开发人员工具上?

3 个答案:

答案 0 :(得分: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;
};

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

答案 1 :(得分: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

答案 2 :(得分:0)

请参阅一个小例子,了解如何捕获异常:

&#13;
&#13;
try {
 alert("proper alert!");
    aert("error this is not a function!");
}
catch(err) {
    document.getElementById("demo").innerHTML = err.message;
}
&#13;
<body>

<p id="demo"></p>

</body>
&#13;
&#13;
&#13;

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

相关问题