Dan*_*ink 14 logging elmah client-side
我正在使用ELMAH来记录我的.net错误.它工作得很好,但我想扩展错误记录以包括客户端错误,即任意JavaScript错误.我可以使用window.onerror事件捕获错误,然后调用.net处理程序(.ashx)来记录elmah中的错误,但这只是我解决问题的小问题.有没有更好的方法将客户端错误记录到elmah?
rbj*_*325 10
这是一个更完整的解决方案(我想我从ELMAH网站上抓了它......不记得了)
ErrorLogging.js:
window.onerror = function (msg, url, line) {
logError(msg, arguments.callee.trace());
}
function logError(ex, stack) {
if (ex == null) return;
if (logErrorUrl == null) {
alert('logErrorUrl must be defined.');
return;
}
var url = ex.fileName != null ? ex.fileName : document.location;
if (stack == null && ex.stack != null) stack = ex.stack;
// format output
var out = ex.message != null ? ex.name + ": " + ex.message : ex;
out += ": at document path '" + url + "'.";
if (stack != null) out += "\n at " + stack.join("\n at ");
// send error message
jQuery.ajax({
type: 'POST',
url: logErrorUrl,
data: { message: out }
});
}
Function.prototype.trace = function()
{
var trace = [];
var current = this;
while(current)
{
trace.push(current.signature());
current = current.caller;
}
return trace;
}
Function.prototype.signature = function()
{
var signature = {
name: this.getName(),
params: [],
toString: function()
{
var params = this.params.length > 0 ?
"'" + this.params.join("', '") + "'" : "";
return this.name + "(" + params + ")"
}
};
if (this.arguments)
{
for(var x=0; x<this.arguments.length; x++)
signature.params.push(this.arguments[x]);
}
return signature;
}
Function.prototype.getName = function()
{
if (this.name)
return this.name;
var definition = this.toString().split("\n")[0];
var exp = /^function ([^\s(]+).+/;
if (exp.test(definition))
return definition.split("\n")[0].replace(exp, "$1") || "anonymous";
return "anonymous";
}
Run Code Online (Sandbox Code Playgroud)
布局/母版页:
<script src="@Url.Content( "~/Scripts/ErrorLogging.js" )" type="text/javascript"></script>
<script type="text/javascript">
//This needs to be here to be on everypage
var logErrorUrl = '@Url.Action( "LogJavaScriptError", "Home" )';
</script>
Run Code Online (Sandbox Code Playgroud)
HomeController.cs:
[HttpPost]
public void LogJavaScriptError( string message ) {
ErrorSignal.FromCurrentContext().Raise( new JavaScriptErrorException( message ) );
}
Run Code Online (Sandbox Code Playgroud)
JavaScriptErrorException.cs:
[Serializable]
public class JavaScriptErrorException: Exception{
public JavaScriptErrorException( string message ) : base ( message ){}
}
Run Code Online (Sandbox Code Playgroud)
通过处理 window.onerror 事件捕获所有 javascript 错误,并进行 ajax 调用以手动在 elmah 中记录错误
window.onerror = function (msg, url, linenumber) {
//make ajax call with all error details and log error directly into the elmah database
//show freindly error msg here to user
//hide error from browser
return true;
}
Run Code Online (Sandbox Code Playgroud)
当时没有找到更好的解决方案。
| 归档时间: |
|
| 查看次数: |
5819 次 |
| 最近记录: |