Suppress timeout exceptions in EF Core request by own try-catch? - exception

I'm using EF Core 6 in a .NET 6 project.
Some of my SQL requests leads to a SQL Server timeout. This is not a big deal and I want to catch this exceptions to just produce a warning instead of an error in the logs.
try
{
List<SomeClass> results = dbContext.TableName
.Where ....
.ToList();
}
catch (Exception ex)
{
// log some warning ...
}
The exception is caught and the warning is logged.
BUT: additionally the EF call itself produces an error that is logged/printed out in console.
How can I suppress the exception within the EF database request to let "my" catch be the only one to handle all exceptions?

Related

Actual exception is not getting logged in MVC when host in IIS

I am running one MVC application where i found one exception in specific method. I will provide here complete details about it.
I am loading some third party grid control from view. to load it i used below code:
#{Html.RenderAction("MasterGridAction", "MyController");}
Now when i access this report from development then this view load and it hits this action method where i used some piece of code there it is throwing error, To catch the error i used try catch block in the method where in catch section i used below code to throw the actual exception like below:
catch (Exception ex)
{
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex).Throw(); throw;
}
When exception get catched it sends this to the Application_Error method in global.asax page where i used below code to find out the actual exception like below:
void Application_Error(object sender, EventArgs e)
{
HttpServerUtility server = HttpContext.Current.Server;
if (server.GetLastError() != null)
{
Exception exception = server.GetLastError();
if (exception.GetBaseException() != null)
{
exception = exception.GetBaseException();
ExceptionType(server, exception);
}
else
{
ExceptionType(server, exception);
}
}
}
In this ExceptionType method i get the exception stack and log to the file using "Log4Net". After logging to the file i could see the exception in notepad like below:
Object reference not set to an instance of an object.
Source File: /MyController/MasterGridAction
Stack Trace:
at 3D.Controllers.MyController.MasterGridAction() in D:\MyUser\3D_MVC\Application\3D_OnlyRelease\3D\Controllers\MyController.cs:line 405
--- End of stack trace from previous location where exception was thrown ---
As we can see in above exception it is clearly shown the line number also where this exception get caught.
But once i host this application in IIS server and access the same page then i could see the logged file
There it shows exception like below:
Exception Message: Object reference not set to an instance of an object.
Stack Trace: at 3D.Controllers.MyController.MasterGridAction()
--- End of stack trace from previous location where exception was thrown ---
As you can see the logged exception of IIS server is not having much information when compare to other exception details.
Am i missing anything there to get the complete exception when host in IIS?
Please suggest.
As you can see the logged exception of IIS server is not having much information when compare to other exception details.
This could be because you don't include the PDB files in production.
It might not be a great idea to include them, since that way one can reverse engineer you app with more precision if they hack your server, but it is up to you to decide. I have seen organizations that include them in their production environments.
Try publishing and deploying on a test environment with and without the PDB files to verify this.

Difference between throwing Exception and throwing a specific Exception such as NullPointerException

I am wondering what is the difference between throwing just Exception and throwing a specific Exception such as NullPointer Exception.
To my current knowledge an Exception should be able to catch any type of exception where as using a specific Exception expects that only that exception type can be thrown.
Example:
void test(String testString) throws Exception;
vs
void test(String testString) throws NullPointerException;
If this is correct than to me it makes sense to just always throw Exception and to never name a specific exception. Am I missing something important here? Does it at the very least effect performance at all? A lot of people are looking between throwing and catching exceptions but nobody asks this very basic question.
I do not see a benefit of throwing any exception except Exception.
To start off, Exception is a base type of every Exception. Just like object is for everything.
By throwing a specific Exception you provide more information to the consumer of what has happened.
Imagine scenario where you get a plain Exception without a message, consumer is lost. When for example framework throws a NullReferenceException, then you are aware of a fact that one of your objects does not have a reference which it was trying to access.
This is how you can chain exceptions and make use of their types:
try
{
throw new NotImplementedException();
}
catch(NullReferenceException ex)
{
// Logic for NullReference exception if needed.
}
catch(NotImplementedException ex)
{
// This will be executed.
}
catch(Exception ex)
{
// Will catch every exception.
}
There are at least two reasons why you would want to throw a specific kind of exception:
If a program fails with an exception, you will have more information with which to determine what went wrong. Compare seeing Exception with FileNotFoundException. The latter clearly gives you more information.
In some cases, the code will want to catch certain kinds of exceptions. For example, when working with serial ports, you might want to catch and handle a TimeoutException differently from a NullReferenceException.
The NullPointerException you mentioned is a very good example from the regular Exception because it is a subclass of RuntimeException. Any throwing of (a subclass of) RuntimeException does not have to be caught or declared.
Any other (=not a subclass of RuntimeException) Exception has to be handled in your code by either a try/catch block or a throws declaration. Otherwise, your code will not even compile! That forces you as a developer to handle errors that might pop up.
As for why using different Exception types is useful, consider the following simple example that uses multiple catch statements:
void doDBStuff(){
try {
performStatement(someStatement);
} catch(SQLException e){
//invalid SQL syntax, something is broken
} catch(AuthenticationException e){
//invalid user credentials for the db, inform the user to change these values
}
In this example, two different exceptions end up in two different catch blocks which lets you handle these errors differently.
It's a best practice to throw specific exceptions, instead of a generic one. This is because the caller might want to treat the exceptions differently, for example in a WebApi you might want to return a Bad Request response (400) for a ArgumentNullException, but you might want to return a different result for other types of exceptions. For example you might actually throw a custom NotFoundException and then the controller would catch it and return a Not Found response (404) instead.
Basically if you throw specific exceptions you are allowing the consumer code to handle the different exception scenarios the way they want.

Unable to catch exception in exception strategy Mule ESB

Am getting the below error in the http connector,I need to catch the exception and perform an operation
org.mule.module.http.internal.request.ResponseValidatorException: Response code 503 mapped as failure. Message payload is of type: BufferInputStream
Below is the code i have written inside choice exception
<catch-exception-strategy when="#[exception.causedBy(http.internal.request.ResponseValidatorException)] " doc:name="ResponseValidator Exception Strategy">
But the catch block is not catching the exception
check the root exception message by using #[groovy:message.getExceptionPayload().getRootException().getMessage()]
in default exception block and fetch the root exception details and use it in your choice exception strategy

Exception Thrown From Service Not Being Caught in Controller

In my Grails service I have code like the following:
def createCharge(chargeParams) {
try {
def charge = Charge.create(chargeParams)
} catch (CardException e) {
throw e
}
}
From my controller I do the following:
try {
service.createCharge(chargeParams)
} catch(CardException e) {
}
However, my controller is not catching the re-throwing of the CardException. If I wrap CardException in a RuntimeException via:
throw new RuntimeException(e)
and/or remove the signature from the catch to just catch(e) without typing it, it works, but I lose some information from the exception, like the message.
As a note, CardException is an Exception, not a RuntimeException. I'm not sure if that matters.
Unlike Java, you don't have to declare the (checked) exceptions that are thrown by a Groovy method, because any undeclared checked exceptions are wrapped in an UndeclaredThrowableException. So this:
def createCharge(chargeParams) {
try {
def charge = Charge.create(chargeParams)
} catch (CardException e) {
throw e
}
}
is effectively the same as:
def createCharge(chargeParams) throws UndeclaredThrowableException {
try {
def charge = Charge.create(chargeParams)
} catch (CardException e) {
throw new UndeclaredThrowableException(e)
}
}
the exception thrown by the above, obviously wouldn't be caught by:
try {
service.createCharge(chargeParams)
} catch(CardException e) {
}
But it will be caught by:
try {
service.createCharge(chargeParams)
} catch(e) {
}
Because this is just a shorthand for:
try {
service.createCharge(chargeParams)
} catch(Exception e) {
}
Unlike Java, you don't have to declare the (checked) exceptions that are thrown by a Groovy method, because any undeclared checked exceptions are wrapped in an UndeclaredThrowableException.
You seem to imply that Groovy wraps checked Exceptions by a UndeclaredThrowableException, this is not the case. If a Grails Service throws a unchecked Exception the Exception is eventually wrappped by an UndeclaredThrowableException but this is a java.lang.reflection mechanism and will only occur when a proxy class is involved.
This happens to be the case because a Grails Service is involved. I'm not sure how many proxy classes are exactly involved by there is at least one: a class that does the transaction handling (by Spring).
The class will wrap any method in the Service with a transaction and rollback the transaction when a RuntimeException occurs. Spring transaction management by default doesn't rollback in case of a checked Exception.
Java
This makes sense in plain old java, since the developer will see the Exception in the application code and will be warned to do something about it. If the developer is smart he will deal with any Exceptions during the scope of a transaction. If he doesn't rollback the transaction he is basically saying: “In this situation, the data integrity provided by the transaction is not important to me. I will recover from this error in some other way”
Groovy
This doesn't make sense in a Groovy world because the Groovy compiler doesn't enforce the dealing with Exceptions. It in effect treats Exceptions exactly the same way as RuntimeExceptions.
There is however a caveat: The reflection mechanism sees an Exception thrown by the proxy that is not in the method signature of the original Service. This is possible because:
Groovy doesn't enforce handling the Exceptions
A proxy method can always throw any Throwable (check InvocationHandler JavaDoc)
Because the reflection mechanism used is from Java, it must conform to the Java rules. So it will have to wrap the Exception in a RuntimeException,.. in this case a UndeclaredThrowableException.
Grails
Now it gets really tricky because if you call your Service method from a Controller and an Exception occurs. You will see a RuntimeException bubble up (because of some hidden mechanism) but your transaction will not be rolled back (because of some hidden mechanism).
This behaviour is very dangerous as the developer really has to remember to properly deal with any Exceptions (which the compiler will not help with) or the developer has to make sure that any Service is properly instructed with #Transactional(rollbackFor = Throwable).
This is a design issue that I think the developers of Grails have overlooked when they first designed this. But I think the default behaviour is so wrong and so dangerous this should really be changed.
I think the simple solution to the problem is to add a throws CardException statement to the service method, thus the exception will no longer be wrapped in UndeclaredThrowableException and the controller will catch the proper exception type.
Just catch the UndeclaredThrowableException, get the message from it, and then re-throw if need be.
catch (UndeclaredThrowableException e) {
def s = e.getUndeclaredThrowable().getMessage()
// do something with the message
throw e
}
The above code fragment will just catch the exception you've explicitly thrown in the code (eg CardException). For example a NullPointerException will not be caught and bubble up.

Best way to Handle Exceptions in C# Catch Block

Best way to Handle Exceptions in C# Catch Block.I have no other choice but to Log the error to SQL DB in Catch block.Howver i am wondering what is the best way to catch exception if caught in Catch block itself?
I would create a separate class to handle error reporting, and expose a function to handle logging the error in the DB.
I found this guide useful:
http://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
Some code that I have used in the past looks like:
try{
throw;
}
catch(Exception ex){
LoggingClass.LogError(some paramaters,ex.tostring());
}
and then your logging class could look like
public static class LoggingClass {
public static void LogError(some paramaters, ex.tostring()){
//try to log to database
//catch and report error in some other way
}
}
I used this article as a reference in the past because I liked the idea of logging to a text file (in the event of a DB error) and then displaying a "nice" message to the user.
C# best practice error handling and passing error messages