ответ

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 wri Функция тэ 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 { 
    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 
} 

Как видно из названия, вы пытаетесь выполнить код в блоке «попробовать». Если возникает ошибка, вы можете выполнять определенные задачи (например, регистрировать ошибку определенным образом) в блоке «catch».

Многие другие варианты: вы можете иметь несколько «улов» блоков в зависимости от типа ошибки, которая была брошена и т.д. Более подробная информация здесь: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

+0

спасибо за ответ, но я хочу чтобы поймать любое исключение в такой функции, как window.onerror, даже если я использовал блоки захвата try, без каких-либо изменений в коде приложения! – Pedram

+0

Я не уверен, что понимаю, чего вы хотите достичь. Вы хотите обрабатывать все свои ошибки в одной функции? Тогда вы не ответили на свой вопрос? Не влияет ли window.onerror ваши потребности? – TanguyP

+0

Да, вы понимаете, но window.onerror не возникает, когда мы используем блоки try/catch в коде. – Pedram

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>

поместить ваш код в блок попробовать и попытаться поймать ошибку поймать блока.

+0

спасибо за ваш ответ, но я хочу поймать любое исключение в такой функции, как window.onerror, даже если бы я использовал блоки захвата try, без каких-либо изменений в коде приложения! – Pedram

Смежные вопросы