如何在JavaScript中记录异常 [英] How to log exceptions in JavaScript

查看:103
本文介绍了如何在JavaScript中记录异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为C#开发人员,我习惯了以下风格的异常处理:

  try 
{
throw SomeException(hahahaha!);
}
catch(Exception ex)
{
Log(ex.ToString());
}

输出
------

SomeNamespace.SomeException:hahahaha!
在ConsoleApplication1.Main()在ConsoleApplication1\Program.cs:行27

它的真的很简单,但告诉我需要知道什么是异常以及它在哪里。我的

如何在JavaScript中实现异常对象的等效事物本身可能只是一个字符串。我真的想能够知道异常发生的确切代码行,但是以下代码根本不记录任何有用的代码:

  try 
{
var WshShell = new ActiveXObject(WScript.Shell);
return WshShell.RegRead(HKEY_LOCAL_MACHINE\\\Some\\\Invalid\\Location);
}
catch(ex)
{
Log(捕获异常:+ ex);
}

输出
------

捕获异常:[对象错误]

编辑(再次):只是为了澄清,这是内部应用程序,大量使用JavaScript。我在从生产系统中可能遇到的JavaScript错误中提取有用的信息之后,我已经有了一个记录机制,只是想要一种获得一个合理的字符串来记录的方式。

解决方案

几乎可以以相同的方式使用,例如。

 尝试
{
throw new Error(hahahaha!);
}
catch(e)
{
alert(e.message)
}

但是,如果要获取行号和文件名,其中抛出错误,我想没有crossbrowser解决方案。消息和名称是Error对象的唯一标准属性。在mozilla你也有lineNumber和fileName属性。


As a C# developer I'm used to the following style of exception handling:

try
{
    throw SomeException("hahahaha!");
}
catch (Exception ex)
{
    Log(ex.ToString());
}

Output
------

SomeNamespace.SomeException: hahahaha!
    at ConsoleApplication1.Main() in ConsoleApplication1\Program.cs:line 27

Its really simple, and yet tells me everything I need to know about what the exception was and where it was.

How do I achieve the equivalent thing in JavaScript where the exception object itself might just be a string. I really want to be able to know the exact line of code where the exception happened, however the following code doesn't log anything useful at all:

try
{
    var WshShell = new ActiveXObject("WScript.Shell");
    return WshShell.RegRead("HKEY_LOCAL_MACHINE\\Some\\Invalid\\Location");
}
catch (ex)
{
    Log("Caught exception: " + ex);
}

Output
------

Caught exception: [object Error]

EDIT (again): Just to clarify, this is for internal application that makes heavy use of JavaScript. I'm after a way of extracting useful information from JavaScript errors that may be caught in the production system - I already have a logging mechanism, just want a way of getting a sensible string to log.

解决方案

You can use almost in the same manner ie.

try
{
    throw new Error("hahahaha!");
}
catch (e)
{
    alert(e.message)
}

But if you want to get line number and filename where error is thrown i suppose there is no crossbrowser solution. Message and name are the only standart properties of Error object. In mozilla you have also lineNumber and fileName properties.

这篇关于如何在JavaScript中记录异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆