fix: added some error handling for YAML headers

This commit is contained in:
Dylan R. E. Moonfire 2022-07-18 20:06:08 -05:00
parent 42cae6b133
commit e029fc12f8
2 changed files with 46 additions and 5 deletions

View file

@ -1,3 +1,4 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text; using System.Text;
@ -30,6 +31,8 @@ public class ParseYamlHeader<TModel> : OperationBase
this.RemoveHeader = true; this.RemoveHeader = true;
} }
public Func<Entity, string, Exception, ParseYamlHeaderErrorHandling>? EntityError { get; set; }
/// <summary> /// <summary>
/// Gets or sets a value indicating whether the header should be removed /// Gets or sets a value indicating whether the header should be removed
/// and the text content be removed. /// and the text content be removed.
@ -52,10 +55,18 @@ public class ParseYamlHeader<TModel> : OperationBase
// Process through the files. We only care about the text ones // Process through the files. We only care about the text ones
// and we'll put a default TModel in for those that don't have a // and we'll put a default TModel in for those that don't have a
// header. // header.
return input.SelectEntity<ITextContent>( return input
( .SelectEntity<ITextContent>(
entity, (
content) => this.Parse(entity, content, deserializer)); entity,
content) => this.Parse(entity, content, deserializer));
}
public ParseYamlHeader<TModel> WithEntityError(Func<Entity, string, Exception, ParseYamlHeaderErrorHandling>? value)
{
this.EntityError = value;
return this;
} }
/// <summary> /// <summary>
@ -138,8 +149,24 @@ public class ParseYamlHeader<TModel> : OperationBase
// Pull out the model so we can append it later. // Pull out the model so we can append it later.
string yaml = buffer.ToString(); string yaml = buffer.ToString();
TModel? model;
TModel? model = deserializer.Deserialize<TModel>(yaml); try
{
model = deserializer.Deserialize<TModel>(yaml);
}
catch (Exception exception)
{
ParseYamlHeaderErrorHandling disposition = this.EntityError?.Invoke(entity, yaml, exception)
?? ParseYamlHeaderErrorHandling.Throw;
if (disposition == ParseYamlHeaderErrorHandling.Ignore)
{
return entity;
}
throw;
}
// If we are not removing the header, then we're done. // If we are not removing the header, then we're done.
if (!this.RemoveHeader) if (!this.RemoveHeader)

View file

@ -0,0 +1,14 @@
namespace Nitride.Yaml;
public enum ParseYamlHeaderErrorHandling
{
/// <summary>
/// Throw an exception if an error happens.
/// </summary>
Throw,
/// <summary>
/// If an error happens, then include without additional processing.
/// </summary>
Ignore,
}