2011-10-11 48 views
0

例外贯穿我的工作在API错误处理使用的组件:是否可以从异常字符串中剥离调用堆栈?

catch (Exception ex) 
{ 
    // ex.ToString() below may be something like "database is locked" 
    string error = string.Format(
     "Error when trying to create a playlist: {0}", ex.ToString()); 
    throw new Exception(error); 
} 

基本上是一个较低等级组件将抛出与错误的详细细节的Exception,这将在更高的被抓使用更通用的,用户友好的错误消息。

当我的客户端应用程序处理此应用程序时,它会调用ex.ToString()以获取完整的错误字符串,但它也包含调用堆栈。

Error: exceptions.RuntimeError: Error when trying to create a playlist: 
System.Exception: database is locked 
at <very large call stack here> 

有一种简单的方法,以防止最后一节(即at <very large call stack here>)从出现在该错误消息,而无需解析字符串?这将返回给用户,我希望错误以用户为中心,而不是以应用程序为中心。

回答

2

尝试使用Exception.Message代替Exception.ToString

string message = string.Format(
    "Error when trying to create a playlist: {0}", ex.Message); 
throw new YourException(message, ex); 
+0

太容易了 - 谢谢。任何防止在开始时显示“exceptions.RuntimeError”的方法。即我只想要显示原始错误字符串。 – LeopardSkinPillBoxHat

+0

@LeopardSkinPillBoxHat:我怀疑它的答案是相同的......在显示异常时使用Exception.Message。你能发布你用来显示异常的代码吗? –

+0

我的歉意 - 这是一个Python包装器,它将这个额外的文本添加到错误字符串的开头。谢谢你的帮助。 – LeopardSkinPillBoxHat