Within a class I have to following code which occurs several times:
var message = $"My Message with Value1='{value1}' and Value2='{value2}'.";
Log.Error(exception, message);
throw new CustomException(message);
message is always different, but the approach of logging the error and throwing an exception is always the same.
Now both Rider and ReSharper within Visual Studio give the following warning: Message template is not a compile time constant.
I can refactor it into this and the warning goes away:
const string messagePattern = "My Message with Value1='{0}' and Value2='{1}'.";
var messageParameters = new object[] { value1, value2 };
Log.Error(exception, messagePattern, messageParameters);
throw new CustomException(string.Format(messagePattern, messageParameters));
But how can I make this code reusable to avoid that I have to repeat the logging and throwing? This is what I'd like to do:
const string messagePattern = "My Message with Value1='{0}' and Value2='{1}'.";
var messageParameters = new object[] { value1, value2 };
LogAndThrow(exception, messagePattern, messageParameters);
void LogAndThrow(Exception exception, string messagePattern, string messageParameters)
{
Log.Error(exception, messagePattern, messageParameters);
throw new CustomException(string.Format(messagePattern, messageParameters));
}
But this gives the same error because messagePattern is not a const anymore and declaring it as in string messagePattern doesn't help.
Is there any way to make this code reusable except disabling the warning?
Currently, your code will throw an exception if the value of value1 is (for example) "{0}". Basically your first piece of code is is not considering what it passes in to be a format string with placeholders, but an already formatted string. You shouldn't call string.Format with that.
I would suggest you provide overloads for LogAndThrow and CustomException that have a single string parameter (for the already-formatted message) and no additional messageParameters parameter (because you don't need it), which does not call string.Format.
To get rid of the warning message should be "My Message with ..." without the $.
Your comments confused me and I came up with the following snippet that contains your desired code. I'm not reviewing your method here, I am addressing the issue of the incorrect use of $.
The result is My Message with Value1='1' and Value2='A'. and not warning (or error if this was .net 5) about message not being a constant.
// BTW. Changed 'string' to 'object[]'
static void LogAndThrow(Exception exception, string messagePattern, object[] messageParameters)
{
//Log.Error(exception, messagePattern, messageParameters);
throw new Exception(string.Format(messagePattern, messageParameters));
}
static void Main()
{
try
{
const string messagePattern = "My Message with Value1='{0}' and Value2='{1}'."; // No $
var messageParameters = new object[] { 1, "A" };
LogAndThrow(new Exception("X"), messagePattern, messageParameters);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I am trying to check that an exception that I throw gives the correct error message.
I have a method in a class that withdraws (substracts) from a value. If the value is less than 0, I throw an exception.
if (amount < 0)
{
throw new System.ArgumentOutOfRangeException("amount", AmountLessThanZeroMessage);
}
This is my error message:
public const string AmountLessThanZeroMessage = "Amount is less than zero";
However, when I try to write a unit test to see if I get the correct message, it fails because of the parameter. This is the test:
[Fact]
public void CannotWithdrawLessThanZero()
{
// Arrange
var account = new Account("User", 23);
// Act
account.DepositCash(100);
var thrownException = Assert.Throws<ArgumentOutOfRangeException>(() => account.WithdrawCash(-10));
// Assert
Assert.Equal(Account.AmountLessThanZeroMessage, thrownException.Message);
}
The result includes the parameter in the end, resulting in a failed test:
It seems the actual message includes which parameter it refers to. How do I correct this message? Should I just add the line (Parameter 'amount') to the expected string, or are there any better options?
You can create the exact same exception and use its message property. Like the code below
[Fact]
public void CannotWithdrawLessThanZero()
{
// Arrange
var account = new Account("User", 23);
var expectedException = new System.ArgumentOutOfRangeException("amount", AmountLessThanZeroMessage);
// Act
account.DepositCash(100);
var thrownException = Assert.Throws<ArgumentOutOfRangeException>(() => account.WithdrawCash(-10));
// Assert
Assert.Equal(expectedException.Message, thrownException.Message);
}
Messages changes often, message can be localized, so testing message equality will make tests more fragile.
Instead you can test that correct exception type was thrown, or even better and create domain specific exception to be sure that exception have been thrown for correct reasons.
public class WithdrawOfNegativeAmountNotAllowedException : Exception
{
public WithdrawOfNegativeAmountNotAllowedException(int amount)
: base($"Amount is less than zero ({amount})")
{
}
}
[Fact]
public void Cannot_withdraw_less_than_zero()
{
var account = new Account("User", 23);
account.DepositCash(100);
Action withdraw = () => account.WithdrawCash(-10);
withdraw.Should().Throw<WithdrawOfNegativeAmountNotAllowedException>();
}
In case you still want to test for correct message. Assertions of strings can be done in multiple ways, I would suggest to make assertion as loose as possible.
Test for part of the message which unlikely will change. For example test that message starts with some text or contain critical value.
[Fact]
public void Cannot_withdraw_less_than_zero()
{
var account = new Account("User", 23);
account.DepositCash(100);
Action withdraw = () => account.WithdrawCash(-10);
withdraw.Should()
.Throw<WithdrawOfNegativeAmountNotAllowedException>()
.And
.Message.Should().ContainEquivalentOf("Amount is less than zero");
}
I have created a SSIS custom data flow component that performs the simple task of converting dates from a COBOL mainframe date types, that are in the format of CYYMMDD, to a SQL Server supported format of YYYYMMDD. There are error rows because the incoming COBOL formatted dates can be invalid dates (i.e., 2-29-2015, 4-31-2016, 9-31-2010, etc). These bad dates are from user derived input fields that do not have a date mask on them and I cannot add a date mask because the application belongs to a 3rd party data vendor.
My problem:
The custom component will not re-direct error rows. I found a posting on MSDN that explains how to re-direct error rows:
https://msdn.microsoft.com/en-us/library/ms136009.aspx
I used this code as a guide and modified it to suit my needs of being able to execute over multiple selected input columns (MS's example only contemplates one input column). When I execute the process, I get the following two errors:
[ConvertCobolDates [2]] Error: System.ArgumentException: Value does not fall within the expected range.
at Microsoft.SqlServer.Dts.Pipeline.Wrapper.IDTSBuffer100.DirectErrorRow(Int32 hRow, Int32 lOutputID, Int32 lErrorCode, Int32 lErrorColumn)
at Microsoft.SqlServer.Dts.Pipeline.PipelineBuffer.DirectErrorRow(Int32 outputID, Int32 errorCode, Int32 errorColumn)
at SSIS.Convert.CobolDate.DataFlow.ConvertCobolDateDataFlow.ProcessInput(Int32 inputID, PipelineBuffer buffer)
at Microsoft.SqlServer.Dts.Pipeline.ManagedComponentHost.HostProcessInput(IDTSManagedComponentWrapper100 wrapper, Int32 inputID, IDTSBuffer100 pDTSBuffer, IntPtr bufferWirePacket)
[SSIS.Pipeline] Error: SSIS Error Code DTS_E_PROCESSINPUTFAILED. The ProcessInput method on component "ConvertCobolDates" (2) failed with error code 0x80070057 while processing input "Input" (4). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running. There may be error messages posted before this with more information about the failure.
Also, I don't know if I am missing code to specifically redirect the output or if the error handling is being done incorrectly - it does not show up in the Configure Error Output screen. Any assistance is greatly appreciated!
enter image description here
Note: I suspect the error is in one of the following places: ProvideComponentProperties or ProcessInput.
public override void ProvideComponentProperties()
{
try
{
// Perform the base class' method
base.ProvideComponentProperties();
// Start out clean, remove anything put on by the base class
base.RemoveAllInputsOutputsAndCustomProperties();
// Set component information
ComponentMetaData.Name = "ConvertCobolDates";
ComponentMetaData.Description = "Data Flow task that converts COBOL date types into SQL Server Date types for each row flowing through the component.";
ComponentMetaData.ContactInfo = "Contact Info.";
ComponentMetaData.UsesDispositions = true; // As a rule, components should support error dispositions - they make it easier to troubleshoot problems with the data
// Create input objects. This allows the custom component to have a 'Success' input data flow line
IDTSInput100 input = ComponentMetaData.InputCollection.New();
input.Name = "Input";
input.ErrorRowDisposition = DTSRowDisposition.RD_RedirectRow; // Use RD_RedirectRow is ComponentMetaData.UsesDispositions = true. Otherwise, use RD_NotUsed
input.ErrorOrTruncationOperation = "Either a bad date has been detected or an input column(s) has been selected that does not contain dates.";
// Create output objects. This allows the custom component to have a 'Success' output data flow line
IDTSOutput100 output = ComponentMetaData.OutputCollection.New();
output.Name = "Output";
output.SynchronousInputID = input.ID; //Synchronous transformation
output.ExclusionGroup = 1;
// Create output objects. This allows the custom component to have a 'Error' output data flow line
IDTSOutput100 errorOutput = ComponentMetaData.OutputCollection.New();
errorOutput.IsErrorOut = true;
errorOutput.Name = "ErrorOutput";
errorOutput.SynchronousInputID = input.ID;
errorOutput.ExclusionGroup = 1;
}
catch (Exception ex)
{
bool bolCancel = false;
ComponentMetaData.FireError(0, ComponentMetaData.Name, ex.Message, "", 0, out bolCancel);
throw;
}
}
public override void ProcessInput(int inputID, PipelineBuffer buffer)
{
IDTSInput100 input = ComponentMetaData.InputCollection.GetObjectByID(inputID);
// This code assumes the component has two outputs, one the default,
// the other the error output. If the intErrorOutputIndex returned from GetErrorOutputInfo
// is 0, then the default output is the second output in the collection.
int intDefaultOutputID = -1;
int intErrorOutputID = -1;
int intErrorOutputIndex = -1;
int intErrorColumnIndex = -1;
bool bolValidDate = false;
GetErrorOutputInfo(ref intErrorOutputID, ref intErrorOutputIndex);
if (intErrorOutputIndex == 0)
intDefaultOutputID = ComponentMetaData.OutputCollection[1].ID;
else
intDefaultOutputID = ComponentMetaData.OutputCollection[0].ID;
// Process each incoming row
while (buffer.NextRow())
{
try
{
for (int i = 0; i < inputBufferColumnIndex.Length; i++)
{
if (!buffer.IsNull(inputBufferColumnIndex[i]))
{
// Get the name of the current column that is being processed
string strColName = this.ComponentMetaData.InputCollection[0].InputColumnCollection[i].Name;
// Get the current row number that is being processed
int intCurRow = buffer.CurrentRow + 2; // Buffer.CurrentRow is zero bounded and the first row is a header row, which is skipped. Adjust by two to account for this
// Ideally, your code should detect potential exceptions before they occur, rather
// than having a generic try/catch block such as this. However, because the error or truncation implementation is specific to each component,
// this sample focuses on actually directing the row, and not a single error or truncation.
// Get the ID of the PipelineBuffer column that may cause an error. This is required for redirecting error rows
intErrorColumnIndex = this.ComponentMetaData.InputCollection[0].InputColumnCollection[i].ID;
string strCobolDate = buffer.GetString(inputBufferColumnIndex[i]);
string strConvertedCobolDate = ConvertCobolDate(strCobolDate, strColName, intCurRow);
DateTime dtConvertedSQLDate;
// Validate that the date is correct. This detects bad dates (e.g., 2-30-2016, 4-31-2015, etc.) that are inputted from the user
// Throw an error if the date is bad
bolValidDate = DateTime.TryParse(strConvertedCobolDate, out dtConvertedSQLDate);
if (!bolValidDate)
{
// Validation failed, throw an exception and redirect the error row
throw new Exception();
}
else if (bolValidDate)
{
// validation passed. Direct the column back to its corresponding row within the pipeline buffer
buffer[inputBufferColumnIndex[i]] = dtConvertedSQLDate.ToShortDateString();
}
}
}
// Unless an exception occurs, direct the row to the default
buffer.DirectRow(intDefaultOutputID);
}
catch(Exception)
{
// Has the user specified to redirect the row?
if (input.ErrorRowDisposition == DTSRowDisposition.RD_RedirectRow)
{
// Yes, direct the row to the error output.
buffer.DirectErrorRow(intErrorOutputID, 0, intErrorColumnIndex);
}
else if (input.ErrorRowDisposition == DTSRowDisposition.RD_FailComponent || input.ErrorRowDisposition == DTSRowDisposition.RD_NotUsed)
{
// No, the user specified to fail the component, or the error row disposition was not set.
throw new Exception("An error occurred, and the DTSRowDisposition is either not set, or is set to fail component.");
}
else
{
// No, the user specified to ignore the failure so direct the row to the default output.
buffer.DirectRow(intDefaultOutputID);
}
}
}
}
After some pain staking research, and help from a friend, the problem has been identified - the errorCode of 0 (specified on the MSDN article I previosuly posted) that is being passed into the DirectErrorRow function is incorrect [it is actually a negative number (in this case: -1071628258)]. This was a difficult bug to fix because the compiler was outputting a generic out of bounds error without specifying both the argument and value that was out of bounds (see below).
'System.ArgumentException: Value does not fall within the expected range.' ... message truncated to reduce post length
I thought that the compiler error was referring to the actual bad date that it was unable to convert and so I spent all of my time focusing on the intErrorColumnIndex, which the MSDN article lists as:
// TODO: Add code to include the intErrorColumnIndex.
I assumed that the errorCode of 0 that was provided by Microsoft was correct. On a hunch, my friend said to try retrieving the actual error code and that worked! Thus, the errorCode is probably bounded somewhere between negative infinity to -1. Microsoft's MSDN article on directing error rows needs to be corrected.
Me: 1
Microsoft: 0
The solution is as follows in the catch block:
catch(Exception)
{
// Has the user specified to redirect the row?
if (input.ErrorRowDisposition == DTSRowDisposition.RD_RedirectRow)
{
// Yes, get the error code
int DTS_E_ERRORTRIGGEREDREDIRECTION = -1;
unchecked
{
DTS_E_ERRORTRIGGEREDREDIRECTION = (int)0xC020401E;
}
// Direct the row to the error output
buffer.DirectErrorRow(intErrorOutputID, DTS_E_ERRORTRIGGEREDREDIRECTION, intErrorColumnIndex);
}
else if (input.ErrorRowDisposition == DTSRowDisposition.RD_FailComponent || input.ErrorRowDisposition == DTSRowDisposition.RD_NotUsed)
{
// No, the user specified to fail the component, or the error row disposition was not set
throw new Exception("An error occurred, and the DTSRowDisposition is either not set or is set to fail component.");
}
else
{
// No, the user specified to ignore the failure so direct the row to the default output
buffer.DirectRow(intDefaultOutputID);
}
}
I've been uniting testing two simple examples of compiling CSharpValue activities. One works and the other doesn't I can't figure out why. If someone could point out the issue and optionally a change to correct it if possible.
Details:
The first unit test works SequenceActivityCompile() the second CodeActivityCompile fails with a NotSupportedException (Expression Activity type CSharpValue requires compilation in order to run. Please ensure that the workflow has been compiled.)
I heard somewhere this can be related to ForImplementation but CodeActivityCompile has the same error whether its value is true or false.
This example is a basic adaption of the Microsoft example at: https://msdn.microsoft.com/en-us/library/jj591618(v=vs.110).aspx
This example blog post discussing compiling C# expressions in WF 4+ at length. If anyone reaching this question needs a basic introduction to the topic:
http://blogs.msdn.com/b/tilovell/archive/2012/05/25/wf4-5-using-csharpvalue-lt-t-gt-and-csharpreference-lt-t-gt-in-net-4-5-compiling-expressions-and-changes-in-visual-studio-generated-xaml.aspx
Related Code:
[TestMethod]
public void SequenceActivityCompile()
{
Activity sequence = new Sequence
{
Activities = { new CSharpValue<string>("\"Hello World \"") }
};
CompileExpressions(sequence);
var result = WorkflowInvoker.Invoke(sequence);
}
[TestMethod]
public void CodeActivityCompile()
{
var code = new CSharpValue<String>("\"Hello World\"");
CompileExpressions(code);
var result = WorkflowInvoker.Invoke(code);
}
void CompileExpressions(Activity activity)
{
// activityName is the Namespace.Type of the activity that contains the
// C# expressions.
string activityName = activity.GetType().ToString();
// Split activityName into Namespace and Type.Append _CompiledExpressionRoot to the type name
// to represent the new type that represents the compiled expressions.
// Take everything after the last . for the type name.
//string activityType = activityName.Split('.').Last() + "_CompiledExpressionRoot";
string activityType = "TestType";
// Take everything before the last . for the namespace.
//string activityNamespace = string.Join(".", activityName.Split('.').Reverse().Skip(1).Reverse());
string activityNamespace = "TestSpace";
// Create a TextExpressionCompilerSettings.
TextExpressionCompilerSettings settings = new TextExpressionCompilerSettings
{
Activity = activity,
Language = "C#",
ActivityName = activityType,
ActivityNamespace = activityNamespace,
RootNamespace = null,
GenerateAsPartialClass = false,
AlwaysGenerateSource = true,
ForImplementation = false
};
// Compile the C# expression.
TextExpressionCompilerResults results =
new TextExpressionCompiler(settings).Compile();
// Any compilation errors are contained in the CompilerMessages.
if (results.HasErrors)
{
throw new Exception("Compilation failed.");
}
// Create an instance of the new compiled expression type.
ICompiledExpressionRoot compiledExpressionRoot =
Activator.CreateInstance(results.ResultType,
new object[] { activity }) as ICompiledExpressionRoot;
// Attach it to the activity.
System.Activities.Expressions.CompiledExpressionInvoker.SetCompiledExpressionRoot(
activity, compiledExpressionRoot);
}
When an exception is thrown (while debugging in the IDE), i have the opportunity to view details of the exception:
But in code if i call exception.ToString() i do not get to see those useful details:
System.Data.SqlClient.SqlException (0x80131904): Could not find stored procedure 'FetchActiveUsers'.
[...snip stack trace...]
But Visual Studio has some magic where it can copy the exception to the clipboard:
Which gives the useful details:
System.Data.SqlClient.SqlException was unhandled by user code
Message=Could not find stored procedure 'FetchActiveUsers'.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=1
Number=2812
Procedure=""
Server=vader
State=62
StackTrace:
[...snip stack trace...]
InnerException:
Well i want that!
What would be the contents of:
String ExceptionToString(Exception ex)
{
//todo: Write useful routine
return ex.ToString();
}
that can accomplish the same magic. Is there a .NET function built in somewhere? Does Exception have a secret method somewhere to convert it to a string?
ErrorCode is specific to ExternalException, not Exception and LineNumber and Number are specific to SqlException, not Exception. Therefore, the only way to get these properties from a general extension method on Exception is to use reflection to iterate over all of the public properties.
So you'll have to say something like:
public static string GetExceptionDetails(this Exception exception) {
var properties = exception.GetType()
.GetProperties();
var fields = properties
.Select(property => new {
Name = property.Name,
Value = property.GetValue(exception, null)
})
.Select(x => String.Format(
"{0} = {1}",
x.Name,
x.Value != null ? x.Value.ToString() : String.Empty
));
return String.Join("\n", fields);
}
(Not tested for compliation issues.)
.NET 2.0 compatible answer:
public static string GetExceptionDetails(this Exception exception)
{
PropertyInfo[] properties = exception.GetType()
.GetProperties();
List<string> fields = new List<string>();
foreach(PropertyInfo property in properties) {
object value = property.GetValue(exception, null);
fields.Add(String.Format(
"{0} = {1}",
property.Name,
value != null ? value.ToString() : String.Empty
));
}
return String.Join("\n", fields.ToArray());
}
I first tried Jason's answer (at the top), which worked pretty well, but I also wanted:
To loop iteratively through inner exceptions and indent them.
Ignore null properties and increases readability of the output.
It includes the metadata in the Data property. (if any) but excludes the Data property itself. (its useless).
I now use this:
public static void WriteExceptionDetails(Exception exception, StringBuilder builderToFill, int level)
{
var indent = new string(' ', level);
if (level > 0)
{
builderToFill.AppendLine(indent + "=== INNER EXCEPTION ===");
}
Action<string> append = (prop) =>
{
var propInfo = exception.GetType().GetProperty(prop);
var val = propInfo.GetValue(exception);
if (val != null)
{
builderToFill.AppendFormat("{0}{1}: {2}{3}", indent, prop, val.ToString(), Environment.NewLine);
}
};
append("Message");
append("HResult");
append("HelpLink");
append("Source");
append("StackTrace");
append("TargetSite");
foreach (DictionaryEntry de in exception.Data)
{
builderToFill.AppendFormat("{0} {1} = {2}{3}", indent, de.Key, de.Value, Environment.NewLine);
}
if (exception.InnerException != null)
{
WriteExceptionDetails(exception.InnerException, builderToFill, ++level);
}
}
Call like this:
var builder = new StringBuilder();
WriteExceptionDetails(exception, builder, 0);
return builder.ToString();
This comprehensive answer handles writing out:
The Data collection property found on all exceptions (The accepted answer does not do this).
Any other custom properties added to the exception.
Recursively writes out the InnerException (The accepted answer does not do this).
Writes out the collection of exceptions contained within the AggregateException.
It also writes out the properties of the exceptions in a nicer order. It's using C# 6.0 but should be very easy for you to convert to older versions if necessary.
public static class ExceptionExtensions
{
public static string ToDetailedString(this Exception exception)
{
if (exception == null)
{
throw new ArgumentNullException(nameof(exception));
}
return ToDetailedString(exception, ExceptionOptions.Default);
}
public static string ToDetailedString(this Exception exception, ExceptionOptions options)
{
var stringBuilder = new StringBuilder();
AppendValue(stringBuilder, "Type", exception.GetType().FullName, options);
foreach (PropertyInfo property in exception
.GetType()
.GetProperties()
.OrderByDescending(x => string.Equals(x.Name, nameof(exception.Message), StringComparison.Ordinal))
.ThenByDescending(x => string.Equals(x.Name, nameof(exception.Source), StringComparison.Ordinal))
.ThenBy(x => string.Equals(x.Name, nameof(exception.InnerException), StringComparison.Ordinal))
.ThenBy(x => string.Equals(x.Name, nameof(AggregateException.InnerExceptions), StringComparison.Ordinal)))
{
var value = property.GetValue(exception, null);
if (value == null && options.OmitNullProperties)
{
if (options.OmitNullProperties)
{
continue;
}
else
{
value = string.Empty;
}
}
AppendValue(stringBuilder, property.Name, value, options);
}
return stringBuilder.ToString().TrimEnd('\r', '\n');
}
private static void AppendCollection(
StringBuilder stringBuilder,
string propertyName,
IEnumerable collection,
ExceptionOptions options)
{
stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
var innerOptions = new ExceptionOptions(options, options.CurrentIndentLevel + 1);
var i = 0;
foreach (var item in collection)
{
var innerPropertyName = $"[{i}]";
if (item is Exception)
{
var innerException = (Exception)item;
AppendException(
stringBuilder,
innerPropertyName,
innerException,
innerOptions);
}
else
{
AppendValue(
stringBuilder,
innerPropertyName,
item,
innerOptions);
}
++i;
}
}
private static void AppendException(
StringBuilder stringBuilder,
string propertyName,
Exception exception,
ExceptionOptions options)
{
var innerExceptionString = ToDetailedString(
exception,
new ExceptionOptions(options, options.CurrentIndentLevel + 1));
stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
stringBuilder.AppendLine(innerExceptionString);
}
private static string IndentString(string value, ExceptionOptions options)
{
return value.Replace(Environment.NewLine, Environment.NewLine + options.Indent);
}
private static void AppendValue(
StringBuilder stringBuilder,
string propertyName,
object value,
ExceptionOptions options)
{
if (value is DictionaryEntry)
{
DictionaryEntry dictionaryEntry = (DictionaryEntry)value;
stringBuilder.AppendLine($"{options.Indent}{propertyName} = {dictionaryEntry.Key} : {dictionaryEntry.Value}");
}
else if (value is Exception)
{
var innerException = (Exception)value;
AppendException(
stringBuilder,
propertyName,
innerException,
options);
}
else if (value is IEnumerable && !(value is string))
{
var collection = (IEnumerable)value;
if (collection.GetEnumerator().MoveNext())
{
AppendCollection(
stringBuilder,
propertyName,
collection,
options);
}
}
else
{
stringBuilder.AppendLine($"{options.Indent}{propertyName} = {value}");
}
}
}
public struct ExceptionOptions
{
public static readonly ExceptionOptions Default = new ExceptionOptions()
{
CurrentIndentLevel = 0,
IndentSpaces = 4,
OmitNullProperties = true
};
internal ExceptionOptions(ExceptionOptions options, int currentIndent)
{
this.CurrentIndentLevel = currentIndent;
this.IndentSpaces = options.IndentSpaces;
this.OmitNullProperties = options.OmitNullProperties;
}
internal string Indent { get { return new string(' ', this.IndentSpaces * this.CurrentIndentLevel); } }
internal int CurrentIndentLevel { get; set; }
public int IndentSpaces { get; set; }
public bool OmitNullProperties { get; set; }
}
Top Tip - Logging Exceptions
Most people will be using this code for logging. Consider using Serilog with my Serilog.Exceptions NuGet package which also logs all properties of an exception but does it faster and without reflection in the majority of cases. Serilog is a very advanced logging framework which is all the rage at the time of writing.
Top Tip - Human Readable Stack Traces
You can use the Ben.Demystifier NuGet package to get human readable stack traces for your exceptions or the serilog-enrichers-demystify NuGet package if you are using Serilog. If you are using .NET Core 2.1, then this feature comes built in.
For people who don't want to mess with overriding, this simple non-intrusive method might be enough:
public static string GetExceptionDetails(Exception exception)
{
return "Exception: " + exception.GetType()
+ "\r\nInnerException: " + exception.InnerException
+ "\r\nMessage: " + exception.Message
+ "\r\nStackTrace: " + exception.StackTrace;
}
It does not show the SQLException-specific details you want, though...
There is no secret method. You could probably just override the ToString() method and build the string you want.
Things like ErrorCode and Message are just properties of the exception that you can add to the desired string output.
Update: After re-reading your question and thinking more about this, Jason's answer is more likely what you are wanting. Overriding the ToString() method would only be helpful for exceptions that you created, not already implemented ones. It doesn't make sense to sub class existing exceptions just to add this functionality.
For displaying some details to user you should use ex.Message. For displaying to developers you will probably need ex.Message and ex.StackTrace.
There is no 'secret' method, you could consider Message property to be best fit for user friendly message.
Also be careful that in some case you may have inner exception in exception you catch which would be also useful to log.
You will probably have to manually construct that string by concatenating the various fields you are interested in.
Each left-side name is property in the Exception. If you want to display Message field, you can do
return ex.Message;
Pretty simple. Likewise, the StackTrace can be displayed as below link.
A complete example of StackTrace: http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx
and Exception class: http://msdn.microsoft.com/en-us/library/system.exception.aspx
I think the exception serialization to JSON is nice option. Sample result:
{
"Errors": [{
"Source": ".Net SqlClient Data Provider",
"Number": -1,
"Class": 20,
"Server": "111.168.222.70",
"Message": "A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)"
}
],
"ClientConnectionId": "b1854037-51e4-4943-94b4-72b7bb4c6ab7",
"ClassName": "System.Data.SqlClient.SqlException",
"Message": "A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)",
"Data": {
"HelpLink.ProdName": "Microsoft SQL Server",
"HelpLink.EvtSrc": "MSSQLServer",
"HelpLink.EvtID": "-1",
"HelpLink.BaseHelpUrl": "http://go.microsoft.com/fwlink",
"HelpLink.LinkId": "20476"
},
"InnerException": null,
"HelpURL": null,
"StackTraceString": " at System.Data.SqlClient.SqlConnection.OnError ... DbExecutionStrategy.Execute[TResult](Func`1 operation)",
"RemoteStackTraceString": null,
"RemoteStackIndex": 0,
"ExceptionMethod": "8\nOnError\nSystem.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.Data.SqlClient.SqlConnection\nVoid OnError(System.Data.SqlClient.SqlException, Boolean, System.Action`1[System.Action])",
"HResult": -2146232060,
"Source": ".Net SqlClient Data Provider",
"WatsonBuckets": null
}
If you call ToString on Exception object, you get the class name appended by the message, followed by inner exception and then the stack trace.
className + message + InnerException + stackTrace
Given that, InnerException and StackTrace are only added if they are not null. Also, the fields you have mentioned in the screenshot are not part of standard Exception class. Yes, exception does offer a public property called "Data", that contain additional user-defined information about the exception.
In visual studio that sort of information can be outputted by a debugger visualizer.
I assume that because it is possible to write your own debugger visualizer:
http://msdn.microsoft.com/en-us/library/e2zc529c.aspx
That in theory, if your can reverse engineer the built-in debugger visualizer for exceptions (if your can work out where they are stored) then you could use the same functionality.
EDIT:
Here is a post about where the debugger visualizers are kept: Where do I find Microsoft.VisualStudio.DebuggerVisualizers?
You might be able to use it for your own purposes.