My web server is based on Delphi / DataSnap.
When a server method raises an exception, how can I handle it?
I tried Application.OnException but it does not work because each connection is a new thread and it only works for the IDE thread.
I want to manage them for adding the data in a log file.
UPDATE:
As #Remy Lebeau says, I do not have control aver the creation of the thread. It is a DataSnap based application that works as Web Api server. A TDSServerClass components instances my TServerMethods class. Then, when a web connection arrives, DataSnap creates a new thread and call to my TServerMethods methods. If within the method, a exception is raised, then it is lost because each thread has its stack. With Application.OnException, I only can catch unhandheld exceptions from the IDE thread. What I want to do is to log any handheld exception in a log file.
From the System.Classes.TThread.FatalException documentation:
If the Execute method raises an exception that is not caught and handled within that method, the thread terminates and sets FatalException to the exception object for that exception. Applications can check FatalException from an OnTerminate event handler to determine whether the thread terminated due to an exception.
If an exception occurs in the Execute method of a TThread object its FatalException property is assigned and the thread terminates.
You can check if an exception occurred in a thread implementing its OnTerminate event:
procedure TForm1.YourThreadTerminate(Sender: TObject);
var
ex: Exception;
begin
ex := Exception(TYourThread(Sender).FatalException);
if Assigned(ex) then
//an exception has occurred: your code here
end;
This is how you can assign the event to you thread:
var
yourThread: TYourThread;
begin
yourThread := TYourThread.Create(True);
yourThread.OnTerminate := YourThreadTerminate;
yourThread.Start;
end;
You may need to hook into the exception handling mechanism itself - JCL has code that does that, for example, or you could use third party libraries like madExcept, EurekaLog or others. They also collect stack traces and other info useful to understand what lead to an exception.
I used JCL some time ago in a Datasnap DCOM server to log unhandled exception to a custom event log. If you're going to write to a file, beware of concurrent access, because more than one thread could try to write to it. Also Event Tracing for Windows (ETW) may be a a better, although more complex way, to log to a file for diagnostic purposes.
Anyway, in this kind of applications, it's better to handle "expected" exceptions, and never let them propagate up to a generic handler. Of course, being able to trap and log "unexpected" ones is useful.
Related
We are on CC&B 2.6. We run base process PUPL Payment Upload on 8 threads. Occasionally the process fails on a thread. The other threads run successfully. And when we restart the job, that thread recovers and completes successfully.
The error message shown is:
SQL Error code 000099997 occurred in module CIPPUPFN:HA100 - UPDATE TCTL
Has anyone encountered this?
This problem might have been caused by a bug in the product that handles the interaction of
sessions and the ThreadlocalStorage object. Some session-related state, such
as the map of DBLocalCobolSQLProcessBackend instances was stored on
ThreadlocalStorage, when it should be on FrameworkSession.
If another session is temporarily "pushed" onto ThreadlocalStorage (e.g. via
SessionExecutable>>doInReadOnlySession()) the original session is set aside
but the map of DBLocalCobolSQLProcessBackend was improperly destroyed and could not be restored when the original session was restored.
If a subsequent db-related call from COBOL into Java requires access to an instance of DBLocalCobolSQLProcessBackend, the desired instance was missing and a new, empty one was created, which lead to a NPE in downstream code.
I would like to be able to log unhandled exceptions via configuring log4net.
Is that possible to achieve by only making changes to the config file? if yes, how to do that?
Otherwise if it's not possible, what should I implement in the code to make this happen?
You can't do this with only configuration, you need log the actual exception somewhere. So you need to catch the 'uncatched' exception and them log it.
public static void Main(string[] args)
{
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new
ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);
// Set the unhandled exception mode to force all Windows Forms errors
// to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}
In the handlers you can log to log4net. After that you can switch them on and off with configuration.
However there are some cases that the exception is not catched. For example when there is a failfast called.
I wish to be able to post messages from the main application of a DataSnap automation server to the RemoteDataModule instances created to service clients.
I understand from other forum entires, such as:
Delphi Multi-Threading Message Loop
That messages can be handled in threads without the need to create a Windows handle for the purpose; messages posted with PostThreadMessage.
However the DataSnap TComponentFactory creates a TApartmentThread instance for each RemoteDataModule, and it's Execute method already processes messages:
while GetMessage(msg, 0, 0, 0) do
begin
DispatchMessage(msg);
Unk._AddRef;
if Unk._Release = 1 then break;
end;
I imagine to get this to process any custom message of mine, would mean re-writing the TApartmentThread Execute method.
I have confirmed that creating a window handle to process messages in a RemoteDataModule instance works using the technique described here:
http://delphi.about.com/od/windowsshellapi/a/receive-windows-messages-in-custom-delphi-class-nonwindowed-control.htm
This uses AllocateHWnd, which can be made thread-safe thanks to the work of others:
How can I make AllocateHwnd threadsafe?
Although this presents a solution, I would like to ask; is there a recommended alternative approach?
It would appear that the only other means of processing custom messages in a TApartmentThread instance would be to rewrite the Execute method.
What is the best way in node to handle unhandled expections that are coming out of core node code? I have a background process that runs and crawls web content and will run for long periods of time without issue, but every so often an unexpected exception occurs and I can't seem to gracefully handle it. The usual culprit appears to be some networking issue (lost connectivity) where the http calls I'm making fail. All of the functions that I have created follow the pattern of FUNCTION_NAME(error, returned_data), but in the situations where the error occurs I'm not seeing any of the functions I created in the call stack that is printed out, instead its showing some of the core node modules. I'm not really worried about these infrequent errors and their root cause, the purpose of this posting is just trying to find a graceful way of handling these exceptions.
I've tried putting a try/catch at the top level of my code where everything runs under but it doesn't seem to capture these exceptions. Is it good practice in node to use try/catch within all the lower level functions that use any core code? Or is there some way to globally capture all unhandled exceptions?
Thanks
Chris
UPDATED TO ADD STACK
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: connect Unknown system errno 10060
at errnoException (net.js:642:11)
at Object.afterConnect [as oncomplete] (net.js:633:18)
is there some way to globally capture all unhandled exceptions?
You can catch all exceptions using process.on('uncaughtException'). Listening to this event will avoid the default action of printing the stack and exiting. However be conscious that ignoring exceptions may lead to problems in your app execution.
Link: http://nodejs.org/docs/latest/api/process.html#process_event_uncaughtexception
Pay attention to the documentation advice:
Note that uncaughtException is a very crude mechanism for exception handling. Using try / catch in your program will give you more control over your program's flow. Especially for server programs that are designed to stay running forever, uncaughtException can be a useful safety mechanism.
To catch network errors and avoid the default behavior (printing stack and exit) you have to listen to "error" events.
For example
var net = require('net');
var client = net.connect(80, 'invalid.host', function () {
console.log("Worked");
})
client.on('error', console.log);
I wrote about this recently at http://snmaynard.com/2012/12/21/node-error-handling/. A new feature of node in version 0.8 is domains and allow you to combine all the forms of error handling into one easier manage form. You can read about them in my post and in the docs.
You can use domains to handle callback error arguments, error event emitters and exceptions all in one place. The problem in this specific case is that when you dont handle an error event emitter, node by default will print the stack trace and exit the app.
I've put together a quick error handling file which logs and emails me whenever an unhandled exception is thrown. it then (optionally) tries to restart the server.
Check it out!
I am writing a web service which has to be able to reply to multiple http requests.
From what I understand, I will need to deal with HttpListener.
What is the best method to receive a http request(or better, multiple http requests), translate it and send the results back to the caller? How safe is to use HttpListeners on threads?
Thanks
You typically set up a main thread that accepts connections and passes the request to be handled by either a new thread or a free thread in a thread pool. I'd say you're on the right track though.
You're looking for something similar to:
while (boolProcessRequests)
{
HttpListenerContext context = null;
// this line blocks until a new request arrives
context = listener.GetContext();
Thread T = new Thread((new YourRequestProcessorClass(context)).ExecuteRequest);
T.Start();
}
Edit Detailed Description If you don't have access to a web-server and need to roll your own web-service, you would use the following structure:
One main thread that accepts connections/requests and as soon as they arrive, it passes the connection to a free threat to process. Sort of like the Hostess at a restaurant that passes you to a Waiter/Waitress who will process your request.
In this case, the Hostess (main thread) has a loop:
- Wait at the door for new arrivals
- Find a free table and seat the patrons there and call the waiter to process the request.
- Go back to the door and wait.
In the code above, the requests are packaged inside the HttpListernContext object. Once they arrive, the main thread creates a new thread and a new RequestProcessor class that is initialized with the request data (context). The RequsetProcessor then uses the Response object inside the context object to respond to the request. Obviously you need to create the YourRequestProcessorClass and function like ExecuteRequest to be run by the thread.
I'm not sure what platform you're on, but you can see a .Net example for threading here and for httplistener here.