ExceptionHelper Class

Provides utility methods to construct exception messages.

public static class ExceptionHelper

Methods

NameDescription
FormatObject(object?, string?)Returns a text representation of an object.

FormatObject(object?, string?)

Returns a text representation of an object.

public static string FormatObject(object? obj, string? format = null)

Parameters

obj object?
The object to represent. Can be null.
format string?
An optional format string to apply if obj implements IFormattable.

Returns

string A text representation of obj.

Remarks

This method attempts to never throw exceptions and always return meaningful text, without cluttering exception messages with potentially very long string values, by using the following algorithm:

  • if obj is null, return ExceptionHelper.NullText;
  • if obj is a string, convert it to a quoted string literal, clipping it if longer than 43 characters by leaving the first and last 20 characters separated by an ellipsis (three dots);
  • otherwise, check whether obj implements IFormattable and act accordingly.

If obj implements IFormattable:

  • try to format obj using the specified format and the invariant culture;
  • if an exception is thrown, try again using an empty format string;
  • if another exception is thrown, treat obj as if it didn't implement IFormattable.

If obj does not implement IFormattable:

Keep in mind that instances of nullable value types will be passed boxed and therefore seen as either null or a non-nullable value.

Constants

NameDescription
NullTextThe text used by ExceptionHelper.FormatObject to represent null values.
ToStringEmptyTextThe text used by ExceptionHelper.FormatObject to represent values whose ToString method returns the empty string.
ToStringNullTextThe text used by ExceptionHelper.FormatObject to represent values whose ToString method returns null.

NullText

The text used by ExceptionHelper.FormatObject to represent null values.

public const string NullText = "<null>"

ToStringEmptyText

The text used by ExceptionHelper.FormatObject to represent values whose ToString method returns the empty string.

public const string ToStringEmptyText = "<empty!>"

ToStringNullText

The text used by ExceptionHelper.FormatObject to represent values whose ToString method returns null.

public const string ToStringNullText = "<null!>"