Extract the user-defined Error message from exception - sql

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

Related

How to dig into Exception data in 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);
}
}
}

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 :)

default exception handling

What im trying to do within my project is every time i raise a
try
...
catch ex as exception
...some logging code
end try
Have it so that there is a class predefined somewhere to execute some code when a catch is triggered. not sure if it's possible but it would make my life easier and alot less duplication in my code.
something like
public sub NullReferenceException()
runLogginfunction()
end sub
Thanks
You can't both catch an exception and have it automatically logged. You can have one or the other. For desktop apps, you can use the UnhandledExceptionEventHandler to catch and log exceptions, in ASP.NET you can use the global.aspx to the same thing. Or you can catch the exception, and decide what to do with it -- which can include logging, but will have to be handled manually.
why this would not work?
try
...
catch ex as exception
NullReferenceException(ex)
end try
module allstuff
public sub NullReferenceException(ex as exception)
runLogginfunction(ex)
end sub
end module

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 ?

AspectJ : can I neutralize 'throw' (replace it with log) and continue the method

In below code I want to neutralize the throw and continue the method - Can it be done ?
public class TestChild extends TestParent{
private String s;
public void doit(String arg) throws Exception {
if(arg == null) {
Exception e = new Exception("exception");
throw e;
}
s=arg;
}
}
The net result should be that, in case of the exception triggered (arg == null)
throw e is replaced by Log(e)
s=arg is executed
Thanks
PS : I can 'swallow' the exception or replace it with another exception but in all cases the method does not continue, all my interventions take place when the harm is done (ie the exception has been thrown)
I strongly doubt that general solution exists. But for your particular code and requirements 1 and 2:
privileged public aspect SkipNullBlockAspect {
public pointcut needSkip(TestChild t1, String a1): execution(void TestChild.doit(String))
&& this(t1) && args(a1) ;
void around(TestChild t1, String a1): needSkip(t1, a1){
if(a1==null) //if argument is null - doing hack.
{
a1=""; //alter argument to skip if block.
proceed(t1, a1);
t1.s=null;
a1=null; //restore argument
System.out.println("Little hack.");
}
else
proceed(t1, a1);
}
}
I think that generally what you want makes no sense most cases because if an application throws an exception it has a reason to do so, and that reason almost always includes the intention not to continue with the normal control flow of the method where the exception was thrown due to possible subsequent errors caused by bogus data. For example, what if you could neutralise the throw in your code and the next lines of code would do something like this:
if(arg == null)
throw new Exception("exception");
// We magically neutralise the exception and are here with arg == null
arg.someMethod(); // NullPointerException
double x = 11.0 / Integer.parseInt(arg); // NumberFormatException
anotherMethod(arg); // might throw exception if arg == null
Do you get my point? You take incalculable risks by continuing control flow here, assuming you can at all. Now what are the alternatives?
Let us assume you know exactly that a value of null does not do any harm here. Then why not just catch the exception with an after() throwing advice?
Or if null is harmful and you know about it, why not intercept method execution and overwrite the parameter so as to avoid the exception to begin with?
Speculatively assuming that the method content is a black box to you and you are trying to do some hacky things here, you can use an around() advice and from there call proceed() multiple times with different argument values (e.g. some authentication token or password) until the called method does not throw an exception anymore.
As you see, there are many ways to solve your practical problem depending on what exactly the problem is and what you want to achieve.
Having said all this, now let us return to your initial technical question of not catching, but actually neutralising an exception, i.e. somehow avoiding its being thrown at all. Because the AspectJ language does not contain technical means to do what you want (thank God!), you can look at other tools which can manipulate Java class files in a more low-level fashion. I have never used them productively, but I am pretty sure that you can do what you want using BCEL or Javassist.