瀏覽代碼

Check parameters and add friendly exceptions.

release/3.x.x
PMExtra 4 年之前
父節點
當前提交
763d9778bb
共有 1 個檔案被更改,包括 14 行新增2 行删除
  1. +14
    -2
      Source/MQTTnet/Extensions/UserPropertyExtension.cs

+ 14
- 2
Source/MQTTnet/Extensions/UserPropertyExtension.cs 查看文件

@@ -7,12 +7,24 @@ namespace MQTTnet.Extensions
{
public static string GetUserProperty(this MqttApplicationMessage message, string propertyName, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
{
return message?.UserProperties?.SingleOrDefault(up => up.Name.Equals(propertyName, comparisonType))?.Value;
if (message == null) throw new ArgumentNullException(nameof(message));
if (propertyName == null) throw new ArgumentNullException(nameof(propertyName));

return message.UserProperties?.SingleOrDefault(up => up.Name.Equals(propertyName, comparisonType))?.Value;
}

public static T GetUserProperty<T>(this MqttApplicationMessage message, string propertyName, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
{
return (T) Convert.ChangeType(GetUserProperty(message, propertyName, comparisonType), typeof(T));
var value = GetUserProperty(message, propertyName, comparisonType);

try
{
return (T) Convert.ChangeType(value, typeof(T));
}
catch (Exception ex)
{
throw new InvalidOperationException($"Cannot convert value({value}) of UserProperty({propertyName}) to {typeof(T).FullName}.", ex);
}
}
}
}

Loading…
取消
儲存