Returning the error details to the calling function after catching an exception in Postgresql - database

I'm adding exception handling to PostgreSQL stored procedures in order to automatically rollback the transactions after an error occurs.
My problem is that once I catch the exception, then I cannot return the details of the error to the calling C program which uses libpq.
The Severity, SQLSTATE, Primary, Detail and Hint are all null. Is there a way to return these after catching the exception?
The libpq function I use to collect these values is PQresultErrorField().

Given than an exception will automatically make a postgresql transaction roll back, why catch it at all? Catching exceptions is usually only useful if you want to usefully recover from the error, not propagate it.

I have recently posted a complete solution how to add a CONTEXT to error messages on dba.SE. The trick is to call a function that raises the error / warning / notice/ etc.
I realize now that your case may be different. My workaround is for adding a CONTEXT to exceptions that you raise yourself.
If you catch an exception to do stuff before the transaction is rolled back, you may want to add a RAISE without parameters at the end of your exception block:
RAISE;
The manual about RAISE:
The last variant of RAISE has no parameters at all. This form can only
be used inside a BEGIN block's EXCEPTION clause; it causes the error
currently being handled to be re-thrown.
However, as #araqnid pointed out, there is not use in an exception block if you are going to propagate the error anyway and everything is rolled back. This solution is only useful for the rare cases where certain changes are persistent and cannot be rolled back, like dblink calls ...

Related

I have issues with the design of onException handled(true) in apache camel

onException(NullPointerException.class)
.handled(true)
.to("google-pubsub:some_topic");
In here, my design is such that for any unforseen error,I want to put the problem message to gcp pubsub error topic.
But I am saying "handled" as true.Hence for any error in publishing to pubsub error topic (say network error etc),the error will be silently ignored !! This is no good for me.Now I lost the message because since it was handled,the message has been acknowledged automatically and the message will not be redelivered by gcp pubsub !!
Please let me know my alternatives
I was just going through the Camel in Action Book.Below is the text
"Camel doesn’t allow further error
handling while already handling an error(onException handled is true) . In other words, when
Camel detects that another
exception was thrown during error handling, it prevents any further action
from taking place. This is done by the
org.apache.camel.processor.FataFallbackErrorHandler, which catches the
new exception, logs a warning, sets this as the exception on the Exchange, and
stops any further routing."
This mean if an exception is thrown while handling an exception,the exception will not be propagated,but a warning will be logged and sets an exception on the exchange.
Since an error has been marked in the exchange ,the pub sub message in the exchange will not be marked as Acked,and will be redelivered by pubsub.
Let me test it my self.
Request-reply pattern
If the caller knew operation has failed, they can retry so you will not mark the exception as handled
One-way pattern and can afford to lose message
Just like java catch block that catches but doesn't re-throw. May be you log a message. Since you can afford to lose the message, it is fine.
One-way pattern, you prefer moving the message somewhere on best of efforts
Exactly like your example. You prefer moving somewhere but if the error hapens on the onException route, you are ok to lose the message
One-way pattern and you cannot afford to lose message
In case of recoverable error, you want to retry a few times but after that you want to move it somewhere else. In the case of irrecoverable error, you want to move it somewhere else straight away. In both cases, if you don't move it, you will endup with infinite loop and your route will be busy repeatedly consuming the same message while others are ignored.
Since you cannot afford to lose the message if the error happens on the onException route, you cannot mark it as handled and at the same time, you cannot let it go back and start a infinite loop
So your option here is Dead Letter Channel error handler
DeadLetterChannel
When the DeadLetterChannel moves a message to the dead letter endpoint, any new Exception thrown is by default handled by the dead letter channel as well. This ensures that the DeadLetterChannel will always succeed.
Reference
https://camel.apache.org/components/latest/eips/dead-letter-channel.html
Note:
As you can see in the image, DeadLetterChannel is another error handler
Move the exception handling logic to new route and use queue/direct component to handle it. In case of failure you can write your failed message to an error/dlq and come up with a strategy to reprocess them.
Main Route:
onException(Exception.class)
.handled(true)
.to("queue:myapp.exception.handler");
from(direct:mainRoute")
.process("processTransaction")
.to("sql:***");
Exception Handler Route:
onException(Exception.class)
.handled(true)
.maximumRedeliveries(2)
.redeliveryDelay(30000)
.to("queue:myapp.exception.handler.failed") ;
from("queue:myapp.exception.handler")
.to("google-pubsub:some_topic");

Uipath try/catch problem - throwing system exception

Having some trouble with try/catch in UiPath:
Got two different projects with their own workflows, with try catch implementations exactly the same in both.
However, one of the try/catch is working absolutely fine, whereas the other one is giving troubles with the following error when I Throw an exception, and then the steps defined in the catch block doesn't even trap it and execute.
Thoughts/Suggestions will be much appreciated - Thanks!
RemoteException wrapping System.Exception: <My user defined message>
at System.Activities.Statements.Throw.Execute(CodeActivityContext context)
at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.ActivityInstance.Execute(ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)
If you have been using the Try Catch with the general Exception, it should be working in the same way in any project.
I believe you was a bit confused by the running mode.
So I assume in one project you fired the project in the debug mode. This stops on the exception when it occurs. If happening you need to hit the continue button.
But if you run the project with the Run button, it will ignore the exception handling as breakpoint and will continue now without any break.
So make sure in a live test you always run it with the run button and not with the usual debug button.

Why to use multiple catch blocks?

We can use multiple catch block in Try-Catch.
But my Question is : why to use multiple catch blocks when it can be done by using single catch block?
Suppose I want exact cause of my problem, I can get that by Ex.message
If I want to show customized message to user, I can show it by putting If-Else loop on Ex.Message.
Thanks in advance.
To handle the individual exception accordingly.
For example:
If your program is handling both database and files. If an SQLException occurs, you have to handle it database manner like closing the dbConnection/reader etc., whereas if a File handling exception then you may handle it differently like file closing, fileNotFound etc.
That is the main reason in my point of view.
For point numbers 1 and 2:
If showing error message is you main idea then you can use if..else. In case if you want to handle the exception then check the above point of my answer. The reason why I stretch the word handling is because it is entirely different from showing a simple error message.
To add some quotes I prefer Best Practices for Handling Exceptions which says
A well-designed set of error handling code blocks can make a program
more robust and less prone to crashing because the application handles
such errors.
This works only if all exceptions share the same base class, then you could do it this way.
But if you do need exception type specific handling, then I would prefer multiple try-catch blocks instead of one with type-depending if-else ...
You can also ask why do we need the Switch - Case. You can do it with If - Else.
And why do you need Else at all. You can do it with If (If not the first condition, and...).
It's a matter of writing a clean and readable code.
By using single catch clock you can catch Exception type - this practice is strongly discouraged by Microsoft programming guidelines. FxCop has the rule DoNotCatchGeneralExceptionTypes which is treated as CriticalError:
Catching general exception types can hide run-time problems from the library user, and can complicate debugging.
http://code.praqma.net/docs/fxcop/Rules/Design/DoNotCatchGeneralExceptionTypes.html
The program should catch only expected exception types (one ore more), leaving unexpected types unhandled. To do this, we need possibility to have multiple catch blocks. See also:
Why does FxCop warn against catch(Exception)?
http://blogs.msdn.com/b/codeanalysis/archive/2006/06/14/631923.aspx

Silverlight 3 XamlReader Exception not caught

when I use XamlReader.Load() with an invalid XAML string, the resulting XAMLParseException is not caught although beeing in a try-catch-block:
try
{
UIElement xamlCode = XamlReader.Load(XamlText) as UIElement;
}
catch (Exception ex)
{
ErrorText = ex.Message;
}
The code is called from the Tick-Event of a DispatcherTimer, but also in Events like MouseLeftButtonDown the exception is not caught resulting in a break in the Line where I call .Load().
Does anyone know how to catch this Exception and resume normal programm activity?
Thanks, Andrej
It is completely unfathomable that this code would not catch the exception. How do you determine that the XAMLParseException is occuring here? Are you sure is not coming from some other Xaml Load in the project?
Is this always the case ? or onlys while debugging ?
I'm aware this is an extremely late answer and you might have found the solution to it, for as reference to people finding your question similar to theirse (like my case ), my answer might still be of use.
If its happening while debuggin, it might be because the exeption is configured to be thrown.
You can change this:
Customize the Debug menu, adding the "Exceptions" command to it.
In the Exceptions configuration, Drill down to System.Windows.Markup.XamlParseException, which is under Common Language Runtime Exceptions.
Remove the check from the "Throw" column.
There are various Silverlight operations that get "re-marshalled" onto separate threads for what are presumably various good and sufficient reasons. It looks kind of like this:
Dispatcher.BeginInvoke(() => LoadSomeXamlOrSomething());
Any exception thrown within LoadSomeXamlOrSomething() won't be caught by normal try/catch blocks. This happens even in SL 4 with things like loading images with invalid formats. It's annoying, and MS needs to come up with a better way to handle this, for instance, by letting you register an exception handler when you make the call.
Until MS figures this out, your options are:
Fix the underlying XAML error.
Catch the exception in App.Application_UnhandledException.

Exceptions inside repositories: how do you handle them?

An easy one that I am interested in getting your thoughts on:
With your repository implementations, do you like to let exceptions be thrown inside the repository and leave the exception handling to the caller, or do you prefer to catch exceptions inside your repository, store the exception and return false/null?
It Depends.
Do I let exceptions bubble up? Absolutely. But I want this for connection failure, command failures. Whatever you do, don't just hide these, you need to know about them. I prefer my applications to fail as quickly as possible to reduce side-effects and further damage.
I also log exceptions. I use Log4net to help with this. But I like to log exceptions at the source. I will let them bubble up from there.
Return null? If something cannot be found (i.e. looking for something by id and it isn't there), then I return null, not an exception. But there are cases where I could see throwing a new exception when this happens.
Main point: exceptions should be 'exceptional', not the rule. If an exception is thrown, it should be because something is really wrong and you need to fix it.
I usually let exceptions leak, though if I'm in a particularly Enterprisey mood I'll wrap them in a RepositoryException to keep clients from caring about the underlying storage engine.
I would never return false/null instead of an exception, as there's already a meaning behind those values.
In rare cases, you could have a brain-dead storage engine that generates exceptions on non-exceptional cases - and I would catch those specific ones and return null if appropriate (eg., if a row does not exist, but the storage engine throws an error on that case - I'd catch it and return null).

Resources