First, I know - there are a lot of online resources that talk about the topic Exception handling - but yet there is still something that's unclear to me.
Consider having this code in an external library, called from another project.
public Task<List<Ident>> GetFoo(){
List<Ident> idents = new List<Ident>();
idents = await IdentRepo.GetIdents(); // some rest-API call with HttpClient..
return idents;
}
At some point I'd like to implement some sort of exception handling - e.g if the webservice I'm connecting to is not available. I could do something like
public Task<List<Ident>> GetFoo(){
List<Ident> idents = new List<Ident>();
try{
idents = await IdentRepo.GetIdents(); // some rest-API call with HttpClient..
} catch (HttpRequestException e){
Diag.Log(e);
}
return idents;
}
I don't like that approach because the caller doesn't know that the webservice request failed and doesn't know if the list is actually empty or if something else happened.
A better solution would be something like this
public Task<List<Ident>> GetFoo(){
List<Ident> idents = new List<Ident>();
try{
idents = await IdentRepo.GetIdents(); // some rest-API call with HttpClient..
} catch (HttpRequestException e){
Diag.Log(e);
throw;
}
return idents;
}
Now the caller has to handle the exception as well. That would work BUT I don't like the idea of the caller knowing the specific type of the exception. The caller doesn't care if it's a rest API request with HTTP or if I'm loading the data from a local file - if it fails it fails.
So - imo - the best solution would be to throw a custom exception.
public Task<List<Ident>> GetFoo(){
List<Ident> idents = new List<Ident>();
try{
idents = await IdentRepo.GetIdents(); // some rest-API call with HttpClient..
} catch (HttpRequestException e){
Diag.Log(e);
throw new IdentProviderNotAvailable();
}
return idents;
}
With that code the only has to care about the IdentProviderNotAvailable Exception. It doesn't matter if I add any new Exception types in the catch block as I only throw IdentProviderNotAvailable.
Is that a good approach? Should I include the stack-trace of the original exception or is there a better way to deal with this?
HttpRequestException(or whatever exception it might be) to theInnerExceptionof yourIdentProviderNotAvailable. and secondly, it's convention to putExceptionon the end of the name of all exceptions. Whether that's a good convention or not is another issue entirely ;)