From 763d9778bb66bf131960d9281d243d9a826219a5 Mon Sep 17 00:00:00 2001 From: PMExtra Date: Thu, 2 Apr 2020 17:29:00 +0800 Subject: [PATCH] Check parameters and add friendly exceptions. --- .../MQTTnet/Extensions/UserPropertyExtension.cs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/Source/MQTTnet/Extensions/UserPropertyExtension.cs b/Source/MQTTnet/Extensions/UserPropertyExtension.cs index b4c83b4..8918600 100644 --- a/Source/MQTTnet/Extensions/UserPropertyExtension.cs +++ b/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(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); + } } } }