I'm having trouble to get a status code from a HttpRequestException on netstandard 2.1 at the catch block. At the .NET Framework there is an extra property "StatusCode", but I can't find any similar for netstandard. Is there any alternative?
Thanks in advance.
I already tried to convert a HttpRequestException into a WebException. Catching a WebException does not trigger the catch.
As already mentioned in comments to your OP, the StatusCode property was introduced in .NET 5 and won't be available in .NetStandard. This means you have to "do it yourself".
You can include the status code value in the existing exception without having to create and maintain a new exception type by leveraging the Data dictionary like this (change the names to your liking):
public static class HttpResponseMessageExtensions
{
public static void MyEnsureSuccessStatusCode(this HttpResponseMessage httpResponseMessage)
{
try
{
httpResponseMessage.EnsureSuccessStatusCode();
}
catch (HttpRequestException ex) when (ex.SetStatusCode(httpResponseMessage.StatusCode))
{
// Intentionally left empty. Will never be reached.
}
}
}
public static class HttpRequestExceptionExtensions
{
private const string StatusCodeKeyName = "StatusCode";
public static bool SetStatusCode(this HttpRequestException httpRequestException, HttpStatusCode httpStatusCode)
{
httpRequestException.Data[StatusCodeKeyName] = httpStatusCode;
return false;
}
public static HttpStatusCode? GetStatusCode(this HttpRequestException httpRequestException)
{
return (HttpStatusCode?)httpRequestException.Data[StatusCodeKeyName];
}
}
Note the usage of an always-false exception filter there. This ensures modifying the original exception doesn't incur severe costs as it retains the original exception as is (it is never "caught" there)
You can then use the new extension instead of the original EnsureSuccessStatusCode to throw the exception:
// grab real response here
var response = default(HttpResponseMessage);
response.MyEnsureSuccessStatusCode();
And you can grab the status code from the exception object using the GetStatusCode extension on whoever is catching the exception upstream.
If you want to make this even more robust, and ensure that you only call GetStatusCode on an exception that was thrown using the custom overload, you can also add a "marker" value in the dictionary to indicate that it was thrown using the extension and act on that (for example, throw an InvalidOperationException saying the method can only be used in conjunction with MyEnsureSuccessStatusCode).
Related
I try to implement code for error handling from Newtonsoft Documentation
I am using the following JsonSerializerSettings
errors = new JsonErrors();
jsonSerializerSettings = new JsonSerializerSettings
{
Error = delegate (object sender, ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
}
};
I use the following code to deserialize the response.
try
{
deserializedObject = JsonConvert.DeserializeObject(response, jsonSerializerSettings);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
If add some extra chars at the end of the response string i expect to catch deserialize exception but actually i see relevant error added to JsonErrors object.
Can i be sure that any error raised by de-serialization/serialization will be catched by JsonSerializerSettings mechanism.
Can i remove the try a catch in code?
In theory all exceptions should be caught and passed to the handler (other than exceptions that cannot be caught such as StackOverflowException.) If you go to the github source and search for IsErrorHandled you will see that all types of exception are caught, for instance here:
catch (Exception ex)
{
if (IsErrorHandled(null, contract, null, reader as IJsonLineInfo, reader.Path, ex))
{
HandleError(reader, false, 0);
return null;
}
else
{
// clear context in case serializer is being used inside a converter
// if the converter wraps the error then not clearing the context will cause this error:
// "Current error context error is different to requested error."
ClearErrorContext();
throw;
}
}
That being said, in practice there may be edge cases where this does not work. For instance, in a previous answer I noted that exceptions thrown from the OnSerializing event of the root object cannot be handled -- though this seems not to be reproducible in the current version (9.0) of Json.NET. But even in the current version, if an exception is thrown trying to create a contract for the root object, Json.NET will not catch and handle it. This could happen because of a buggy custom contract resolver, or because of a mistake in applying serialization attributes to the root object. For instance, trying to serialize or deserialize the following as the root object:
public class BadExtensionData
{
Dictionary<string, object> extensionData;
[JsonExtensionData]
public Dictionary<string, object> ExtensionData { set { extensionData = value; } }
}
will result in an unhandled exception:
Newtonsoft.Json.JsonException: Invalid extension data attribute on 'BadExtensionData'. Member 'ExtensionData' must have a getter.
Thus you may want to leave the outer try/catch just in case (and even report an issue for exceptions that cannot be handled).
Finally, do be aware that catching and swallowing all exceptions is considered bad practice.
After quick source code inspection I tend to say that following sentence is true:
If JsonSerializerSettings is proper (ie. without nasty null references and with configured error handler with Handled property set to true)
and input string is not null (only for deserialization), then try-catch block is redundant.
I have a common method that I'm using to handle a specific error that may come back from a number of functions:
protected async Task<T> RunMyMethod<T>(Func<T> method)
{
try
{
var returnValue = await Task.Run<T>(method);
return returnValue;
}
catch (MyCustomException)
{
// Force a clean shutdown of the software
ShutdownApplication();
return default(T);
}
}
Here's an example of how that is then used in a derived class:
private async Task<IEnumerable<MyData>> GetMyData()
{
var returnValue = await base.RunMyMethod<IEnumerable<MyData>>(() =>
{
var returnval = GetMyDataFromServer();
return returnval;
});
return returnValue;
}
When an exception of type MyCustomException occurs in GetMyDataFromServer() the software doesn't drop into the catch block. I get the following error in the function GetMyData():
An exception of type 'System.ServiceModel.FaultException`1' occurred in mscorlib.dll but was not handled in user code
Additional information: Exception of type 'MyCustomException' was thrown.
This is with only User-unhandled exceptions turned on.
GetMyDataFromServer() communicates with a WCF service. This service is what throws the error.
ChannelFactory<TChannel> cf = new ChannelFactory<TChannel>(endPointName);
Binding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
var clientCredentials = new ClientCredentials();
. . .
channel = cf.CreateChannel();
var data = channel.CallWCFService();
Having looked around on-line, it appeared that the correct way to handle this was to change the base method as follows:
protected async Task<T> RunMyMethod<T>(Func<T> method)
{
var returnValue = await Task.Run<T>(method).ContinueWith(e =>
{
ShutdownApplication();
return default(T);
}, TaskContinuationOptions.OnlyOnFaulted);
return returnValue;
}
When I run this, I'm obviously not trapping for the correct error message, but I'm just getting a TaskCancellationException.
So, I have two questions: is my conclusion about how to handle this exception correct and, if so, how do I trap a specific error; and why am I getting a TaskCancellationException?
You get TaskCancellationException because the continuation is cancelled as it's conditional (i.e. TaskContinuationOptions.OnlyOnFaulted) and the condition isn't met since the antecedent task wasn't faulted.
There's no reason to use that method of adding a continuation. Using async-await like you did at the start is good enough (and even simpler).
The issue is that you are trying to catch MyCustomException but that isn't the exception being thrown. Since you're using WCF the exception is FaultException. You can check the "real" exception stored in FaultException.InnerException.
I am building a ASP.NET Web Api service and I would like to create centralized exception handling code.
I want to handle different types of exceptions in different ways. I will log all exceptions using log4net. For some types of exceptions I will want to notify an administrator via email. For some types of exceptions I want to rethrow a friendlier exception that will be returned to the caller. For some types of exceptions I want to just continue processing from the controller.
But how do I do that? I am using an Exception Filter Attribute. I have this code working. The attribute is registered properly and the code is firing. I just want to know how I can continue if certain types of exceptions are thrown. Hope that makes sense.
public class MyExceptionHandlingAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
//Log all errors
_log.Error(myException);
if(myException is [one of the types I need to notify about])
{
...send out notification email
}
if(myException is [one of the types that we continue processing])
{
...don't do anything, return back to the caller and continue
...Not sure how to do this. How do I basically not do anything here?
}
if(myException is [one of the types where we rethrow])
{
throw new HttpResponseException(new HttpResponseMessage(StatusCode.InternalServerError)
{
Content = new StringContent("Friendly message goes here."),
ReasonPhrase = "Critical Exception"
});
}
}
}
For some types of exceptions I want to just continue processing from the controller. But how do I do that?
By writing try..catch where you want this behaviour to occur. See Resuming execution of code after exception is thrown and caught.
To clarify, I assume you have something like this:
void ProcessEntries(entries)
{
foreach (var entry in entries)
{
ProcessEntry(entry);
}
}
void ProcessEntry(entry)
{
if (foo)
{
throw new EntryProcessingException();
}
}
And when EntryProcessingException is thrown, you actually don't care and want to continue execution.
If this assumption is correct: you can't do that with a global exception filter, as once an exception is caught, there's no returning execution to where it was thrown. There is no On Error Resume Next in C#, especially not when the exceptions are handled using filters as #Marjan explained.
So, remove EntryProcessingException from your filter, and catch that specific exception by changing the loop body:
void ProcessEntries(entries)
{
foreach (var entry in entries)
{
try
{
ProcessEntry(entry);
}
catch (EntryProcessingException ex)
{
// Log the exception
}
}
}
And your loop will happily spin to its end, but throw on all other exceptions where it will be handled by your filter.
Is there a way to check if exception is handled on a higher application level to skip logging and re-throw? Like this, for example:
try
{
// Execute some code
}
catch (Exception e)
{
if(!ExceptionIsHandled())
LogError(e);
throw e;
}
Nothing that I'm aware of. If you're committed to this design (see note at end), you could write a wrapper for an Exception that's some sort of HandledException and just make its InnerException be the one that was thrown. Then you could make your code look like:
try
{
// Execute some code
}
catch (HandledException e)
{
LogError(e.InnerException);
// Do something else
}
catch (Exception e)
{
throw ;
}
Here comes the stereotypical Stackoverflow "you're doin it wrong" part of the answer...
However, if you've truly "handled" the exception, it doesn't make a lot of sense to be re-throwing it. Maybe your method should just return a failure result, possibly including the Exception as a detail item for what went wrong.
This is old, but I do have some input here. There is a design pattern I've used before that does this very well, but does add a little bit of overhead to everything.
Basically, all methods would return a response object (e.g., Response<T>). Any exceptions that occur should be wrapped in the response object and returned instead of thrown.
public class Response<T>
{
public T Payload { get; set; }
public bool IsSuccessful { get; set; } = false;
public string Message { get; set; }
public Exception Error { get; set; }
}
public class MyService
{
public Response<IEnumerable<Customer>> GetCustomers()
{
var response = new Response<IEnumerable<Customer>>();
try
{
var customers = new List<Customer>()
{
new Customer() { CompanyName = "ABC Co." },
new Customer() { CompanyName = "ACME" }
};
response.Payload = customers;
response.IsSuccessful = true;
}
catch (Exception e)
{
response.IsSuccessful = false;
response.Error = e;
// A friendly message, safe to show to users.
response.Message = "An error occurred while attempting to retrieve customers.";
}
return response;
}
}
You can bubble up the exception without rethrowing it, and handle appropriately. You can then add exception catches for more custom user-friendly messages.
I also use a custom base Exception type for any errors that are safe to show the client. This way I can add a generic catch at the controller level to propagate those prepared error messages.
Well no, hasn't got there yet has it. Exceptions bubble up through handlers.
Usual way to go about this.
Is define your own exceptions, then only catch the ones you are going to handle where you are.
If you could be certain that code was wrapped within a specially-designed try-catch block which was written in a language that supports exception filters, it would be possible to determine before or during stack unwinding whether the exception was likely to be caught by that outer block or by an inner one. The usefulness of this is rather limited, however, especially given the extremely common anti-pattern of code catching and rethrowing exceptions that it knows it's not going to resolve, simply for the purpose of finding out that they occurred.
If your goal is simply to avoid redundant logging, I'd suggest that you should use a logging facility which can deal efficiently with redundancy. While some people might argue that it's better to have exceptions logged just once at the outer layers, there are advantages to having more logging opportunities. If an exception occurs within the inner layer and a middle layer swallows it, logging code within the outer layer will never find out about it. By contrast, if the inner layer starts out by capturing the exception and arranging for it to get logged, then even if the middle layer swallows the exception the fact that it occurred could still get recorded.
So, I have a list containing a custom class, MyClass
MyClass has properties, which can be null (but aren't meant to be).
When this class is sorted, using a custom sorter, where the sorter accesses this null property and throws an exception, the exception is considered unhandled, even though there is a try-catch block around the sort method.
Now for some reason the exception still gets written to the console, which is what the exception handler is doing.
I have a real application with this same issue, causing my unit tests to fail, even though the exception is handled correctly and I cannot explain this.
So I have attached some sample code to explain myself better, run this from VS.
Updated Code
Results:
System.InvalidOperationException
Failed to compare two elements in the array.
Done!
So it seems to be handling my custom exception, and throwing its own?
using System;
using System.Collections.Generic;
using System.Data;
namespace TestSortException
{
class Program
{
static void Main()
{
try
{
var list = new List<MyClass>
{
new MyClass("1"),
new MyClass(null),
new MyClass("fdsfsdf")
};
list.Sort(new MyClassSorter());
}
catch(Exception e)
{
Console.WriteLine(e.GetType());
Console.WriteLine(e.Message);
}
Console.WriteLine("Done!");
Console.ReadLine();
}
}
class MyClassSorter : IComparer<MyClass>
{
public int Compare(MyClass x, MyClass y)
{
// try
// {
if (x.MyString == y.MyString)
return 0;
// Unhandled??? Exception here
if (x.MyString.Length > y.MyString.Length)
return 1;
return -1;
// }
// catch (Exception)
// {
// return -1;
// }
}
}
class MyClass
{
private string _myString;
public string MyString
{
get
{
if (_myString == null) throw new DataException("MyString is Null");
return _myString;
}
}
public MyClass(string myString)
{
_myString = myString;
}
}
}
There's a try/catch block round the Sort method, yes - and that catch block catches the exception. In other words, Sort throws an exception and your catch block catches it. It doesn't propagate out beyond Main - so "Done!" is printed.
This is exactly what I'd expect. In what way is it "unhandled" in your experience? Were you expecting Sort not to throw the exception? It needs to do something to indicate the failure to compare two elements, and this seems to be the most appropriate course of action.
In what way are your unit tests failing? Are you deliberately giving them invalid data? How do you want your comparison code to react to invalid data? If it should ignore it (and return a comparison based on another property), then you should actively check the property rather than letting an exception propagate. In most cases I'd rather allow the exception if this indicates that there's a bug earlier on though.
EDIT: Based on your other comments, it sounds like you're doing the appropriate thing, letting the exception bubble up - but it's not clear in what way you're seeing the exception not be handled.
If you're running in the debugger, it may be breaking on the exception being thrown, but that doesn't mean it won't be handled. Try either changing your exception settings or running without the debugger.
EDIT: Yes, Sort will catch the exception and throw an InvalidOperationException instead - but you can use the InnerException property of that exception to get hold of the original one. It's unfortunate that the documentation doesn't specify this :(
For example, when it checks that string "1" isn't equal to null. But it wants then to compare lengths of "1" string and null => which is impossible.
I assume you work with .Net Framework 4.0. The new thing there is that a NullRefenrenceException can not be caught any more (similar to OutOfMemory exception).