Re: c++ check if service is running
On Thursday, October 11, 2012 12:51:14 AM UTC+2, Mick wrote:
Hi there,
I posted this in mongodb-user, but I think it's more of a C++ question, s=
o sorry for the double-post...
I'm using Visual Studio 2008 C++, connecting to Mongo 2.0.6 database.
If I try to get a ScopedDbConnection, but mongod is not running for some =
reason, it throws
"First-chance exception at 0x750bb9bc in myApp.exe: Microsoft C++ excepti=
on: mongo::SocketException at memory location 0x0057ead8"
Is there any way to check if either of those 2 are running (mongod or Mon=
goDB) before trying to get a ScopedDbConnection?
Maybe, but it's a bad idea. It's akin to going to a supermarket to see whet=
her there's milk, going back home to get the money, then going to the super=
market again to buy it.
What you should do instead is to catch the exception, inspect it, and repor=
t the error. E.g. (I don't know anything about mongo, so I might be way off=
base here).
try
{
ScopedDbConnection db(...);
use(db); // lots of code here ;-)
}
catch(const mongo::SocketException& e)
{
// inspect e._type here to see what to do next.
}
Another reason why trying to see whether a "service is running" (not mongo,=
ANYTHING) is that it is surprisingly hard to do well. It's hard because th=
ere's literally thousands of reasons why you can't connect. If that is so, =
it is by far the best to actually try to connect, and report to the user an=
ything you have in the line of info (in this case e.g. toString() and the a=
ddress you tried to reach if it isn't in exception object already).
Note that the approach like this: (don't know if possible here, but have se=
en people doing this):
auto_ptr<ScopedConnection> P;
try
{
P = auto_ptr<ScopedConnection>(new ScopedConnection(...));
}
catch(whatever)
{
reporterror;
}
if (P)
{ // mongo alive, yay!
use(*P);
}
is an abomination. It's ugly, and you still need another try/catch to repor=
t errors that will eventually come from use.
So... Don't detect anything. Fail eagerly, loudly and clearly instead.
HTH,
Goran.