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.IO;
using System.Text;
@ -30,6 +31,8 @@ public class ParseYamlHeader<TModel> : OperationBase
this.RemoveHeader = true;
}
public Func<Entity, string, Exception, ParseYamlHeaderErrorHandling>? EntityError { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the header should 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
// and we'll put a default TModel in for those that don't have a
// header.
return input.SelectEntity<ITextContent>(
(
entity,
content) => this.Parse(entity, content, deserializer));
return input
.SelectEntity<ITextContent>(
(
entity,
content) => this.Parse(entity, content, deserializer));
}
public ParseYamlHeader<TModel> WithEntityError(Func<Entity, string, Exception, ParseYamlHeaderErrorHandling>? value)
{
this.EntityError = value;
return this;
}
/// <summary>
@ -138,8 +149,24 @@ public class ParseYamlHeader<TModel> : OperationBase
// Pull out the model so we can append it later.
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 (!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,
}