how to use class to catch error in Log4net? - class

I use Log4net to catch errors. I want to create class and use it to catch errors. I don't want to catch error through TRY CATCH. How can I do it

Log4Net is supposed for logging facilities. And it could be used for logging exceptions.
But it cannot be used to catch exceptions.
If you want to log exceptions you need to use try catch then you can log caught exception via Log4Net.

Related

Exception handling by using try and finally

if i want Hndle exception in apex by using try and finally bock without catch block how can i do that?am trying to do through dev console bt its not handling exception throwing error

Production Code's General try-catch Eats nUnit Assertion Exceptions Causing the Failing Tests to Pass

I understand that nUnit failed Assert statements throw an exception, and that's how Test runners detect an error has occurred. My problem is that there is a general try-catch block in the production code that eats these Assert exceptions, and the Unity Test runner thinks the code is running without any issue. I've simplified the code to this:
[UnityTest]
public IEnumerator End2EndTests_Test_Foo()
{
try
{
Assert.Fail("Something is wrong.");
}
catch (Exception)
{
UnityEngine.Debug.Log("* Something went wrong. I ate this exception! yum yum *");
}
yield break;
}
As I mentioned, this test passes in Unity Test Runner. What's the remedy?
Note 1: I have not put any assertion inside the production code. The assertions are in callbacks that are invoked by the production code. If any exception happens in the callbacks, the production code catches them. That's how the failed assertion exceptions are caught by production code, not the Test runner.
Note 2: Some background: The production code sends a request to a server. When it receives a response, it invokes all subscribers (=callbacks). My test code has subscribed to the OnResponse event. The failed assertion is inside that callback. The general try-catch is inside the production code, embracing the invocation of the OnResponse event.
Note 3: I don't want to put a special catch statement for nUnit in the production code and re-throw the exception. That's a bad solution because the production code should not have any dependency on a testing framework.
It's OK for your test to subscribe to the callbacks, but you can't assert in the method that the callback invokes. All you can do is record information.
The test itself, after installing the callback should wait for it to be callback to complete and then assert on the saved information.

How to properly handle exceptions in MongoClient for VertX

In the startup method of my application I want to check that the credentials for MongoDB provided to the application are OK. If they are OK, I continue the startup, if not, the application is supposed to exit as it cannot connect to the DB. The code snippet is as below:
// Create the client
MongoClient mongodb = null;
try {
mongodb = MongoClient.createShared(vertx, mongo_cnf, mongo_cnf.getString("pool_name"));
}
catch(Exception e) {
log.error("Unable to create MongoDB client. Cause: '{}'. Bailing out", e.getMessage());
System.exit(-1);
}
If I provide wrong credentials, the catch block is not called. Yet I get the following on the console:
19:35:43.017 WARN org.mongodb.driver.connection - Exception thrown during connection pool background maintenance task
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='user', source='admin', password=<hidden>, mechanismProperties={}}
at com.mongodb.connection.SaslAuthenticator.wrapException(SaslAuthenticator.java:162)
at com.mongodb.connection.SaslAuthenticator.access$200(SaslAuthenticator.java:39)
... many lines
The question is: how to intercept this exception in my code and be able to handle it properly ?
The exception is happening in the mongodb's java driver daemon thread so you cannot catch it.
Vertx MongoClient abstracts you from direct interaction with MongoDB Java driver so you can't modify anything related to the client.
You could access mongo client instance via reflection, but as it's already created you cannot pass additional configuration to it.
If you used com.mongodb.async.client.MongoClient you could pass ServerListener which could access the exception and you could examine it (please see this answer for more details - https://stackoverflow.com/a/46526000/1126831).
But it's only possible to specify the ServerListener in the moment of construction of the mongo client, which happens inside the Vertx MongoClient wrapper and there's no way to pass this additional configuration.
Currently the exception is not thrown, which in my opinion a mistake in design, since you receive an object that you cannot work with. Feel free to open a bug: https://github.com/vert-x3/vertx-mongo-client/issues
What you can do to detect that your client is "dead or arrival" is to wait for connection timeout:
// Default is 30s, which is quite long
JsonObject config = new JsonObject().put("serverSelectionTimeoutMS", 5_000);
MongoClient client = MongoClient.createShared(vertx, config, "pool_name");
client.findOne("some_collection", json1, json2, (h) -> {
if (h.succeeded()) {
//...
}
else {
// Notify that the client is dead
}
});

How to catch connection error on Perl MongoDB driver?

I'm using an official Perl driver for working with mongodb. To catch and handle errors, Try::Tiny and Safe::Isa modules are recommended. However, it doesn't work as expected. Please check code below that should work according to documentation but in fact it doesn't work:
use MongoDB;
use Try::Tiny;
use Safe::Isa;
my $client;
try {
$client = MongoDB->connect('mongodb://localhost');
$client->connect;
} catch {
warn "caught error: $_";
};
my $collection = $client->ns('foo.bar');
try {
my $all = $collection->find;
} catch {
warn "2 - caught error: $_";;
};
As far as connections are established automatically according documentation there will be no exception on connect(). But there is no exception on request too! Also I added $client->connect string to force connection, but again no exception. I'm running this script at machine where there is no mongodb installed and no mongodb docker container running so an exception definitely must appear.
Could someone explain what am I doing wrong?
This is a subtle issue. find returns a cursor object but doesn't issue the query immediately. From the documentation for MongoDB::Collection:
Note, a MongoDB::Cursor object holds the query and does not issue the
query to the server until the `result` method is called on it or until
an iterator method like `next` is called.

Partition is below target replica or instance count

When attempting to publish a Service Fabric application to a local cluster, the cluster fails to load the application stating the error in the title. The stack trace points me to an exception line in OwinCommunicationListener.cs:
try
{
this.eventSource.LogInfo("Starting web server on " + this.listeningAddress);
this.webApp = WebApp.Start(this.listeningAddress, appBuilder => this.startup.Invoke(appBuilder));
this.eventSource.LogInfo("Listening on " + this.publishAddress);
return Task.FromResult(this.publishAddress);
}
catch (Exception ex)
{
var logString = $"Web server failed to open endpoint {endpointName}. {ex.ToString()}";
this.eventSource.LogFatal(logString);
this.StopWebServer();
throw ex; // points to this line from cluster manager
}
I am unable to inspect the exception thrown, but there is no useful exception information other than a TargetInvocationException with a stack trace to the line noted above. Why won't this application load on my local cluster?
It's hard to say without an actual exception message or stack trace but judging by the location from which the exception was thrown and the fact that the problem resolved itself the next morning, the most likely and most common cause of this is that the port you were trying to use to open the web listener was taken by some other process at the time, and the next morning the port was free again. This, by the way, isn't really specific to Service Fabric. You're just trying to open a socket on a port that was taken by someone else.
I'm honestly more curious about why you couldn't inspect the exception. I can think of three things off the top of my head to help with that:
Use "throw" instead of "throw ex" so you don't reset the stack trace.
Look at your logs. It looks like you're writing out an ETW event in your catch block. What did it say?
Use the Visual Studio debugger: Simply set a breakpoint in the catch block and start the application with debugging by pressing F5.