InvalidDataException.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using System;
  2. namespace S7.Net
  3. {
  4. #if NET_FULL
  5. [Serializable]
  6. #endif
  7. public class InvalidDataException : Exception
  8. {
  9. public byte[] ReceivedData { get; }
  10. public int ErrorIndex { get; }
  11. public byte ExpectedValue { get; }
  12. public InvalidDataException(string message, byte[] receivedData, int errorIndex, byte expectedValue)
  13. : base(FormatMessage(message, receivedData, errorIndex, expectedValue))
  14. {
  15. ReceivedData = receivedData;
  16. ErrorIndex = errorIndex;
  17. ExpectedValue = expectedValue;
  18. }
  19. #if NET_FULL
  20. protected InvalidDataException(System.Runtime.Serialization.SerializationInfo info,
  21. System.Runtime.Serialization.StreamingContext context) : base(info, context)
  22. {
  23. ReceivedData = (byte[]) info.GetValue(nameof(ReceivedData), typeof(byte[]));
  24. ErrorIndex = info.GetInt32(nameof(ErrorIndex));
  25. ExpectedValue = info.GetByte(nameof(ExpectedValue));
  26. }
  27. #endif
  28. private static string FormatMessage(string message, byte[] receivedData, int errorIndex, byte expectedValue)
  29. {
  30. if (errorIndex >= receivedData.Length)
  31. throw new ArgumentOutOfRangeException(nameof(errorIndex),
  32. $"{nameof(errorIndex)} {errorIndex} is outside the bounds of {nameof(receivedData)} with length {receivedData.Length}.");
  33. return $"{message} Invalid data received. Expected '{expectedValue}' at index {errorIndex}, " +
  34. $"but received {receivedData[errorIndex]}. See the {nameof(ReceivedData)} property " +
  35. "for the full message received.";
  36. }
  37. }
  38. }