Skip to content

Commit

Permalink
Added system of exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
GreyCat committed Oct 22, 2019
1 parent d8d5e25 commit 28d787d
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions KaitaiStruct.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Text;

namespace Kaitai
{
Expand Down Expand Up @@ -34,4 +35,70 @@ public interface CustomDecoder
/// <param name="src">Source byte array.</param>
byte[] Decode(byte[] src);
}

/// <summary>
/// Common ancestor for all error originating from Kaitai Struct usage.
/// Stores KSY source path, pointing to an element supposedly guilty of
/// an error.
/// </summary>
public class KaitaiStructError : Exception {
public KaitaiStructError(string msg, string srcPath)
: base(srcPath + ": " + msg)
{
this.srcPath = srcPath;
}

protected string srcPath;
}

/// <summary>
/// Common ancestor for all validation failures. Stores pointer to
/// KaitaiStream IO object which was involved in an error.
/// </summary>
public class ValidationFailedError : KaitaiStructError {
public ValidationFailedError(string msg, KaitaiStream io, string srcPath)
: base("at pos " + io.Pos + ": validation failed: " + msg, srcPath)
{
this.io = io;
}

protected KaitaiStream io;

protected static string ByteArrayToHex(byte[] arr) {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < arr.Length; i++)
{
if (i > 0)
{
sb.Append(' ');
}
sb.Append(string.Format("{0:X2}", arr[i]));
}
sb.Append(']');
return sb.ToString();
}
}

/// <summary>
/// Signals validation failure: we required "actual" value to be equal to
/// "expected", but it turned out that it's not.
/// </summary>
public class ValidationNotEqualError : ValidationFailedError {
public ValidationNotEqualError(byte[] expected, byte[] actual, KaitaiStream io, string srcPath)
: base("not equal, expected " + ByteArrayToHex(expected) + ", but got " + ByteArrayToHex(actual), io, srcPath)
{
this.expected = expected;
this.actual = actual;
}

public ValidationNotEqualError(Object expected, Object actual, KaitaiStream io, string srcPath)
: base("not equal, expected " + expected + ", but got " + actual, io, srcPath)
{
this.expected = expected;
this.actual = actual;
}

protected Object expected;
protected Object actual;
}
}

0 comments on commit 28d787d

Please sign in to comment.