Skip to content

Error Handling and Tracking

axunonb edited this page May 17, 2022 · 2 revisions

Error Handling

By default, SmartFormat sets ParseErrorAction.ThrowError for the Parser and FormatErrorAction.ThrowError for the SmartFormatter.

If you change it to Ignore, this can lead to confusing results. It's highly recommended, to turn exceptions on at least while developing and debugging the code:

Smart.Default.Settings.FormatErrorAction = FormatErrorAction.ThrowError;
Smart.Default.Settings.ParseErrorAction = ParseErrorAction.ThrowError;

Also, consider whether it makes sense to OutputErrorInResult or MaintainTokens in the result.

Error Tracking

Besides throwing and catching exceptions it is possible, to trace any formatting or parsing errors by subscribing to the corresponding events.

You can subscribe to the SmartFormatter.OnFormattingFailure and Parser.OnParsingFailure events:

// Smart.Default returns a thread-static SmartFormatter
var badPlaceholders = new HashSet<string>();
Smart.Default.OnFormattingFailure += (sender, args) => { badPlaceholders.Add(args.Placeholder); };

var parsingErrorText = new HashSet<string>();
Smart.Default.Parser.OnParsingFailure += (sender, args) => { parsingErrorText.Add(args.RawText); };

These events fire no matter how FormatErrorAction and ParseErrorAction are assigned in SmartSettings: Opposed to exceptions, all errors will be reported, not only the first failure. Going this way you can decide in your code very finely grained, how to react on errors.

Clone this wiki locally