How to dig into Exception data in VB.NET - vb.net

I'm finding it hard to find the answer to my query in existing answers of Stackoverflow that's why I've decided to ask the question.
I want to handle the error with Try Catch but the default information from e.Message is not what I need.
Basically when using a breakpoint I can see that the Exception object has the data available when I dig in.
The PositionMessage type is string so I want to use this data to feed into Catch behavior. I just can't figure out how to assign the value from this specific field into a variable.
I hope you can help me with this.

The exception may be of type System.Management.Automation.RuntimeException in which case it implements IContainsErrorRecord. This means it has an ErrorRecord property (what you're looking for). You can try to cast it, and if it succeeds, you can access PositionMessage. Else (it's not a RuntimeException), then just treat it as a normal Exception.
Sub Main()
Try
' do stuff
Catch ex As Exception
Dim e = TryCast(ex, IContainsErrorRecord)
Dim message As String
If e IsNot Nothing Then
message = e.ErrorRecord.InvocationInfo.PositionM‌​essage
Else
message = ex.Message
End If
Console.WriteLine(message)
End Try
End Sub

NB: This is C#, but trivial to convert to VB. I do something like this:
results = pipeline.Invoke();
if (pipeline.Error.Count > 0)
{
var errors = pipeline.Error.Read() as Collection<ErrorRecord>;
if (errors != null)
{
foreach (ErrorRecord err in errors)
{
Console.WriteLine(err.InvocationMessage.PositionMessage);
}
}
}

Related

OnError script task not constructing error messages

I have a script task(onError event handler) which gets the system error messages and stores them in the errorMessages user variable. The below script never finishes and goes in loop. I am trying to implement this link for sending email failure notifications. Any thoughts where this is going wrong?
Dim messages As Collections.ArrayList
Try
messages = CType(Dts.Variables("errorMessages").Value, Collections.ArrayList)
Catch ex As Exception
messages = New Collections.ArrayList()
End Try
messages.Add(Dts.Variables("ErrorDescription").Value.ToString())
' MessageBox.Show("Arraylist constructed")
Dts.Variables("errorMessages").Value = messages
'Dts.TaskResult = Dts.Results.Success
Dts.TaskResult = ScriptResults.Success
Check the declaration type of the errorMessages variable. I mistakenly declared it as string but it had to be type object. Changing that resolved the issue. Just posting it here in case someone faces similar issue.

Adding extra data to HttpResponseMessage/Exception (throwing an exception with multiple arguments)

I have an errorbox in my web application that appears whenever a certain type of exception is caught. At the moment the exception is thrown with a string, that I can then insert into my errorbox. I would now like to also give it e.g. a color, so that I (in case of an exception) can set both the color and the text of the errorbox.
Once I catch an exception I throw a new HttpResponseException with a ReasonPhrase and a StatusCode. These are both used whenever I handle the exception. I actually use a custom exception type that currently only has a message called MyException in this example.
It looks like this:
Public Class MyException
Inherits Exception
Public Sub New(message As String)
MyBase.New(message)
End Sub
End Class
I've heard about using some sort of Data or Content property for the HttpResponseMessage, but I don't quite understand how I would use that.
Here's the vb.net code for the catching of an exception:
Catch myEx As MyException
Dim resp = New HttpResponseMessage(HttpStatusCode.ExpectationFailed) With
{
.ReasonPhrase = myEx.Message,
.StatusCode = HttpStatusCode.ExpectationFailed
}
Throw New HttpResponseException(resp)
When I throw the exception to start with, I would want to do something like:
Throw New MyException("Some error text", 5, "yellow", true)
For instance.
And then insert those extra arguments into the HttpResponseMessage somehow.
Any help would be greatly appreciated :)

Extract the user-defined Error message from exception

Inside my stored procedure, i just checked a particular condition and i'll throw Exception if that condition fails. like below,
Raise Exception '%', 'Hello world';
It is working fine, But the error message Hello world also comes with some other error code like stuffs like below in my front end,
DA00014:ERROR: P0001: Hello world
|___________________|
|
I really dont want this part to get displayed in the front end.
Is there any proper way available to filter out/Extract the right message from thrown exception.?
[Note: Please don't suggest me to do some string manipulations.]
DBMS : POSTGRESQL 9.0.3
Driver : Npgsql 1.0
Front End : VB.net
Npgsql Fastpath
If NpgsqlException.Errors is null in your exception handler then you have most likely hit a bug in Npgsql Fastpath (well I consider it a bug anyway). Here is the offending line in version 2 but the same issue exists in version 1.
It basically boils down to this code where a proper NpgsqlError is constructed and then thrown away when raising the exception by calling ToString() on it.
NpgsqlError e = new NpgsqlError(conn.BackendProtocolVersion, stream);
throw new NpgsqlException(e.ToString());
The fix would be as simple as changing the code to this and using the already supported ability of NpgsqlException to take in a list of NpgsqlError in the constructor.
NpgsqlError e = new NpgsqlError(conn.BackendProtocolVersion, stream);
throw new NpgsqlException(new ArrayList(e));
So in summary you can't do it without string manipulation unless you compile your own version of Npgsql patching the issue.
Npgsql
If you aren't using Fastpath then the thrown NpgsqlException object contains an Errors property which should be a non null list. This is an example of extracting the message from the first error.
(ex.Errors[0] as NpgsqlError).Message
try this..
Inside your store procedure place an extra character in message. e.g
Raise Exception '%', '|Hello world';
On Front end split your message on character "|", and display second index of array. e.g
Try
' your code..
Catch ex As Exception
Dim arr As String() = ex.Message.Split("|")
If arr.Count > 1 Then
MessageBox.Show(Convert.ToString(arr(1)))
Else
MessageBox.Show(Convert.ToString(ex.Message))
End If
End Try
If i understood, you can try this once
IF condition match -- (your condition)
BEGIN
RAISERROR('Hello world', 16,16)
return
END
and in expception
can use like
catch(exception ex)
{
// ex.Message
// ex.InnerException.Message
}
This should work:
Catch ex As Exception
lblMsg.Text = ex.Message.Replace("ERROR: P0001: ", "")
End Try

InvalidOperationException is ignored in try/catch block

I have the following coding
try
{
var foundCanProperty = properties
.First(x => x.Name == "Can" + method.Name);
var foundOnExecuteMethod = methods
.First(x => x.Name == "On" + method.Name);
var command = new Command(this, foundOnExecuteMethod, foundCanProperty);
TrySetCommand(foundControl as Control, command);
}
catch (InvalidOperationException ex)
{
throw new FatalException("Please check if you have provided all 'On' and 'Can' methods/properties for the view" + View.GetType().FullName, ex);
}
I'd expected that if the methods.First() (in second var statement) throws an InvalidOperationException, I'd be able to catch it. But this seems not be the case (catch block is ignored and the application terminates with the raised exception). If I throw myself an exception of the same type within the try block, it gets caught. Does Linq use multihreading so that the exception is thrown in another thread? Perhaps I make also a stupid error here and just do not see it :(.
Thanks for any help!
I know that this isn't an answer, but rather some additional steps for debugging, but does it change anything if you instead try to catch the general type "Exception" instead of the IOE? That may help to isolate if the method is truly throwing an IOE, or if its failure is generating an IOE somewhere else in the stack. Also - assuming this method isn't in main() - is there a way to wrap the call to it in a try/catch and then inspect the behavior at that point in the call flow?
Apologies, too, in that I know very little about the SilverLight development environment so hopefully the suggestions aren't far fetched.
InvalidOperationException exception occures when The source sequence is empty.
refere to http://msdn.microsoft.com/en-us/library/bb291976.aspx
check weather "properties" or "methods" is not empty.
out of interest, Why you not using FirstOrDefault ?

is there a way to handle all antlr exception types in a rule catch[...] block

I'm using ANTLR3 with the C runtime.
I'd like to do some custom error handling. What I'm really after is that if there is an antlr matching exception of any kind in a sub rule I'd like to tell ANTLR to skip trying to handle it and let it percolate up to a more global rule.
At that rule I'll log it and then try to resume.
I've set the rule catch method like so, so that all rules won't try to recover.
#rulecatch
{
if (HASEXCEPTION())
{
PREPORTERROR();
}
}
This allows me to insert catch handlers on the rules that i want.
At my rule of interest i can then use the catch syntax like so:
catch [ANTLR3_RECOGNITION_EXCEPTION]
{
PREPORTERROR();
RECOGNIZER->consumeUntil(RECOGNIZER,RCURLY);
CONSUME();
PSRSTATE->error = ANTLR3_FALSE;
PSRSTATE->failed = ANTLR3_FALSE;
}
The problem is that this syntax seems to only allow me to catch one type of exception. I'd like to be able to catch all exception types.
Is there a way to do this?
I thought I could overload all the recovery functions but then some code generates exceptions like so:
CONSTRUCTEX();
EXCEPTION->type = ANTLR3_NO_VIABLE_ALT_EXCEPTION;
EXCEPTION->message = (void *)"";
EXCEPTION->decisionNum = 23;
EXCEPTION->state = 0;
goto rulewhenEx;
which means I'll need to catch all possible exceptions.
Any thoughts??
I've ended up trying two solutions for this.
Approach 1)
Overloading the rulecatch setting to set the exception type to one specific type
#rulecatch
{
if (HASEXCEPTION())
{
// This is ugly. We set the exception type to ANTLR3_RECOGNITION_EXCEPTION so we can always
// catch them.
PREPORTERROR();
EXCEPTION->type = ANTLR3_RECOGNITION_EXCEPTION;
}
}
This allows me to use one catch block as all exceptions will be of that type.
Approach 2)
I just use multiple catch blocks and they all dispatch to a common function to handle the error
catch [ANTLR3_RECOGNITION_EXCEPTION]
{
handleException();
}
catch [ANTLR3_MISMATCHED_TOKEN_EXCEPTION]
{
handleException();
}
....