开发者

Is is possible to strip a call stack from an exception string?

开发者 https://www.devze.com 2023-04-12 07:25 出处:网络
Exceptions are used throughout the component I\'m working in for API error handling: catch (Exception ex)

Exceptions are used throughout the component I'm working in for API error handling:

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(err开发者_运维知识库or);
}

Basically a lower-level component will throw an Exception with detailed specifics of the error, and this will be caught at a higher-level with a more generic, user-friendly error message.

When my client application processes this application, it calls ex.ToString() to get the complete error string, but this also includes the call stack.

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

Is there an easy way to prevent the last section (i.e. at <very large call stack here>) from appearing in the error message, without having the parse the string? This is being returned to the user and I want the error to be user-focused not application-focused.


Try using Exception.Message instead of Exception.ToString:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号