I am running a Dispatcher which handles JSON data. The build is connected to a dictionary of values the JSON looks up against, but on occasion, there will be values which are not present in the dictionary, which will cause the code to error.
The issue is that I do not know which line it is erroring on (and there are a lot of fields on the JSON, so manually checking is very long). Is there an easy way I can either tell which line is being processed when running or be told what the missing field is?
I found some code online, but it kept telling me that âline 0â is where it errored, when not finding the key.
Unfortunately I am unable to share this as it has sensitive data.
But let me give an eg:
A customer enters their title/name into our website: Dr John Smith
This then has the chance of going into several 3rd party portals, but they use different formatting, such as in drop downs, so Dr could be listed as Doctor on one or Doc on another
The dictionary is used to establish which output is needed for each portal.
The issue: if they enter something which doesnât match then it will give us a generic error for that block of code, but I currently cannot determine which field is being looked for.
From Dictionary part go though the different options like:
youDictVar.ContainsKey(YourKey)
yourDictVar.Keys - get all Keys
yourDictVar.Values- get all Values
And we can also work with Set Operations like Intersect, Except to find out what is common or not present, when checking different Sets (Set ~ Collection ~ Array ~ ListsâŚ)
If you surround your code with Try Catch you can print the error message. For .NET Framework 5 or newer the missing key is also displayed in the error message:
Try
'All your code here ...
Dim dict As Dictionary(Of String, String) = new Dictionary(Of String, String)
If (dict("banana") = "yellow") Then
' Good banana
End If
Catch e As Exception
Console.WriteLine(e.Message)
'Rethrow the exception
Throw
End Try
I would like to try this but donât really understand what the banana refers to aha. If it is specific fields in the dictionary, there are probably too many aha
1/ Do not get confused by bananas. Just put all your invoke code in the âtryâ part.
2/ I was also strugning to find meaningfull explanation of error if it occured in invoke code. I found that such description can be found in InnerException attribute of the exception.
Just put your code in the Try-section. Ignore the banana code. It was just an example to trigger an exception. Replace it with your code instead.
Modified the code to print the inner exception message also as @J0ska recommended:
Try
'All your code here ...
Catch e As Exception
Console.WriteLine(e.Message)
If e.InnerException IsNot Nothing Then
Console.WriteLine("Inner exception: " + e.InnerException.Message)
End If
'Rethrow the exception
Throw
End Try