C# how to capture stored procedure exceptions? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Code:
using (var reader = await cmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
var recibir = reader.VisibleFieldCount;
var rear = reader;
response.Add(new Cuota
{
opcion = (int)reader["PC_NUMERO_OPCION"],
cuota = (int)reader["PC_NUMERO_CUOTAS"]
});
}
}
I am trying to get the exceptions of SQL Server, what are the corresponding methods?

In general, you can catch a SQL Exception using the SQLException class. It works like this:
try
{
// your code that calls the database here
}
catch (SqlException e)
{
// your code that handles the Sql Exception
}
I typically add a double catch, just in case there is some other error in my code tht isn't SQL related:
try
{
// your code that calls the database here
}
catch (SqlException e)
{
// your code that handles the Sql Exception
}
catch (Exception ex)
{
// your code that handles normal exceptions
}

Related

Catch specific exception instead of "Exception ex" [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm inserting data to a database and I guess some kind of exceptions might occur here, possible more than one?
ussually I used to write something like this:
try
{
//Execution code
}
catch(Exception ex)
{
// log error and throw it
}
And I think it's better to catch some specific exception instead of (Exception ex) something like this:
try
{
// my possibly bad code which inserts data to db
var someEntity = CreateEntityFromDTO(someDTO);
_context.SomeThing.Add(someEntity);
await _context.SaveChangesAsync(cancellationToken);
}
catch(MySpecificException mse)
{
// log error and throw it
}
What might be best practice when it's about catching exception while inserting data to db ?
Thanks
Cheers
You could make your SpecificExceptions inherit from another higher level DatabaseException and handle all Database Exceptions in one catch clause like
public class DatabaseException : Exception {}
public class MySpecificException : DatabaseException {}
public class YetAnotherDBSpecificException : DatabaseException {}
try
{
// insert data.
}
catch(DatabaseException dbEx)
{
// A database exception occured.
Console.Log(dbEx.Message);
}
catch(Exception other)
{
// Non db exception occured.
Console.Log(other.Message);
}

Try Catch to Handle Exception [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am trying to update some documents in DocumentDb / CosmosDb, and if that fails, need to do something else, and then if that fails to log it out...
try {
do a thing w/ database
}
catch (DocumentClientException dce1) {
try {
do another, alternative thing w/ database
}
catch (DocumentClientException dce2) {
log to app insights.
}
}
I'm not sure about this, it seems clunky.. what do you guys think?
For additional bonus points, I need to do this quite frequently.. so something that I can farm off somewhere would be even better ;)
Personally I'd avoid intermixing exception flow with a functional logic flow. It can get brittle. Instead, convert the exception into a logical flag and use it in ordinary logic constructs.
So step 1 is catch the exception and set a variable or return value based on it, and wrap this in an independent method to mask the messiness from everyone else:
bool TryDoSomethingWithDataBase()
{
try
{
//Do thing that could fail
return true;
}
catch(SpecificException ex)
{
return false;
}
}
bool TryDoSomethingElseWithDataBase()
{
try
{
//Do thing that could fail
return true;
}
catch(SpecificException ex)
{
return false;
}
}
Step 2 is to write the logic as usual:
if (!TryDoSomethingWithDatabase())
{
if (!TryDoSomethingElseWithDatabase())
{
LogFatalError();
}
}
Or
var ok = TryDoSomethingWithDatabase();
if (ok) return;
ok = TryDoSomethingElseWithDatabase();
if (ok) return;
LogFatalError();
Why would your thing with the Database fail? You would be better coding for the conditionals you are aware of and expecting and do different things if you want to go into a different logic for processing the result.
Try catch will catch anything and everything, so if your connection to the db fails etc or if you are trying to read or insert malformed data etc.
Try catch does have various exceptions that you can investigate further and catch the specific exception you are interested in.. e.g.
try
//try something
catch (Exception ex)
{
if (ex is FormatException || ex is OverflowException)
{
//Do something specific;
return;
}
throw;
}
This is ok but if you say you'll have this over and over it's better to extract that logic and reuse it.
One way of doing this is to have a method that accept the first and section actions as parameters, for example:
public void TryThis(Action doFirst, Action doSecond)
{
try {
doFirst();
}
catch (DocumentClientException dce1) {
try {
doSecond();
}
catch (DocumentClientException dce2) {
log to app insights.
}
}
}
And then use it like so:
public void DoSomethig1()
{
...
}
public void DoSomething2()
{
...
}
TryThis(DoSomething1, DoSomething2)

How to check error message in C#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Is that a way to check error message shown after negative values? I can check if the correct exception was thrown, but what if my method won't throw an exception with negative numbers, just WriteLine to Error output stream.
public List<int> MyMethod()
{
...
try
{
//add elements to list
}
catch(Exception e)
{
Error.WriteLine("Element cannot be negative, but other elements are ok");
}
...
}
[TestMethod]
public void TestWithNegatives()
{
try
{
List<int> list = MyMethod();
//there is a negative int in list, so there'll be an error message
}
catch (Exception e)
{
//Can I check here the error message, if there isn't exception thrown in mymethod?
}
}
Since you already handled the exception and it is not rethrown, you cannot handle it again in your test.
But since you know that a message is written to Console.Error, you can check this by redirecting Console.Error to a custom StringWriter and check what was written to it like that:
public void TestWithNegatives()
{
using (StringWriter sw = new StringWriter())
{
Console.SetError(sw);
List<int> list = MyMethod();
// Check output in "Error":
Assert.IsFalse(string.IsNullOrEmpty(sw.ToString()));
}
}

Nested Try and Catch blocks [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have nested try-catch blocks in a custom C# code for SharePoint. I want to execute the code in only one catch block (the inner one) when the code inside the inner try block throws an exception.
try
{
//do something
try
{
//do something if exception is thrown, don't go to parent catch
}
catch(Exception ex) {...}
}
catch(Exception ex)
{ .... }
I know I can use different types of exceptions but that's not what I am looking for.
Summary
If exception occurs, I don't want it to reach the parent catch in addition to the inner catch.
If you don't want to execute the outer exception in that case you should not throw the exception from the inner catch block.
try
{
//do something
try
{
//do something IF EXCEPTION HAPPENs don't Go to parent catch
}
catch(Exception ex)
{
// logging and don't use "throw" here.
}
}
catch(Exception ex)
{
// outer logging
}
The outer catch wouldn't fire if the inner catch handled the exception
If you want the outer catch to fire as well, you'd have to do:
try
{
//do something
try
{
//do something
}
catch(Exception ex)
{
// do some logging etc...
throw;
}
}
catch(Exception ex)
{
// now this will be triggered and you have
// the stack trace from the inner exception as well
}
Essentially, as you have the code there now, the outer catch will not be triggered from the inner try {} catch {}

Handling two WebException's properly [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
Improve this question
I am trying to handle two different WebException's properly.
Basically they are handled after calling WebClient.DownloadFile(string address, string fileName)
AFAIK, so far there are two I have to handle, both WebException's:
The remote name could not be resolved (i.e. No network connectivity to access server to download file)
(404) File not nound (i.e. the file doesn't exist on the server)
There may be more but this is what I've found most important so far.
So how should I handle this properly, as they are both WebException's but I want to handle each case above differently.
This is what I have so far:
try
{
using (var client = new WebClient())
{
client.DownloadFile("...");
}
}
catch(InvalidOperationException ioEx)
{
if (ioEx is WebException)
{
if (ioEx.Message.Contains("404")
{
//handle 404
}
if (ioEx.Message.Contains("remote name could not")
{
//handle file doesn't exist
}
}
}
As you can see I am checking the message to see what type of WebException it is. I would assume there is a better or a more precise way to do this?
Based on this MSDN article, you could do something along the following lines:
try
{
// try to download file here
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
{
// handle the 404 here
}
}
else if (ex.Status == WebExceptionStatus.NameResolutionFailure)
{
// handle name resolution failure
}
}
I'm not certain that WebExceptionStatus.NameResolutionFailure is the error you are seeing, but you can examine the exception that is thrown and determine what the WebExceptionStatus for that error is.

Categories

Resources