I have a series of methods that call wcf services and all of them have the same try catch code
Response Method1(Request request)
{
Response response = null;
using(ChannelFactory<IService1> factory = new ChannelFactory<IService1>(myEndpoint))
{
IService1 channel = factory.CreateChannel();
try
{
response = channel.Operation(request);
}
catch(CommunicationException ex)
{
// Handle Exception
}
catch(TimeoutException ex)
{
// Handle Exception
}
catch(Exception ex)
{
// Handle Exception
}
}
return response;
}
And so on (I have 6 methods like this for different services).. how can i encapsulate all the service calls and handle the exceptions in a single method
EDIT
Following Nathan A's advice I created a simple generic method:
protected TResult ExecuteAndCatch<TResult>(Func<T, TResult> serviceCall, T request)
where T : Request
where TResult : Response
{
try
{
return serviceCall(request);
}
catch (CommunicationException ex)
{
}
catch (TimeoutException ex)
{
}
catch (Exception ex)
{
}
return null;
}
The new methods would like this
Response NewMethod1(Request request)
{
Response response = null;
using(ChannelFactory<IService1> factory = new ChannelFactory<IService1>(myEndpoint))
{
IService1 channel = factory.CreateChannel();
response = channel.Operation(request);
}
return response;
}
and i'm trying to call it like
Response response = ExecuteAndCatch<Response>(NewMethod1, new Request())
What am I doing wrong?
Use a wrapper function.
Take a look at this article: http://mytenpennies.wikidot.com/blog:writing-wcf-wrapper-and-catching-common-exceptions
Here's an example from the article:
private void ExecuteAndCatch<T> (Action<T> action, T t) {
try {
action (t);
Success = true;
}
catch (TimeoutException) {
Success = false;
Message = "Timeout exception raised.";
}
catch (CommunicationException) {
Success = false;
Message = "Communication exception raised.";
}
}
If your client derives from ClientBase<T> e.g MyClient : ClientBase<IWCFService>
You could then create your own base class that provides methods that will wrap the common functionality.
The below sample code could be expanded to allow the final derived class to specify what to do when a particular method call fails. Here I just call HandleError
In specific client class
//method that returns a value
public int Ping()
{
return Protect(c => c.Ping());
}
//void method usage
public void Nothing(int stuff)
{
Protect(c => c.Nothing(stuff));
}
In client base class
protected void Protect(Action<IWCFService> action)
{
Protect(c => { action(c); return true; });
}
//add other exception handling
protected Protect<T>(Func<IWCFService, T> func)
{
try
{
return func(Channel);
}
catch (FaultException e)
{
HandleError(e);//up to you to implement this and any others
}
return default(T);
}
inject the various clients through an interface and then run the operation in a single place?
HttpResponse performOperation(IServiceClient injectedServiceClient)
{
IServiceClient client = injectedServiceClient;
try
{
client.Operation();
}
catch(CommunicationException ex)
{
// Handle Exception
}
catch(TimeoutException ex)
{
// Handle Exception
}
catch(Exception ex)
{
// Handle Exception
}
return httpResponse(httpStatusCode.OK);
}
Related
I have a .NET appplication where there is a controller for receiving user requests, a service Service 1 which calls another service Service 2.
I have some code in the Service 2 where I query the database(DynamoDB) and get a 500 error in response when the user request values are incorrect. I want to handle this such that I catch this error/exception and send back the error message along with a 400 status code from the controller to the user. How should I modify the code to do this?
This is what I have tried. Currently, I'm just printing the error in Service 1 but I need to send it to the controller. Is sending the error message to the controller by throwing exceptions along the way the right way to do it?
The below code is similar to the actual code
Controller:
[HttpGet]
[Authorize(Policy = "Read-Entity")]
[Route("byParams/{param1}/{param2}")]
[Produces(typeof(DynamoResult<EntityResponse>))]
public async Task<IActionResult> ListByParams([FromQuery] DynamoQuery entityQuery)
{
try
{
return await HandleRequest(async () =>
{
return Ok((await _entityStore.ListByParams(entityQuery)));
});
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
Service 1:
public async Task<DynamoResult<EntityResponse>> ListByParams(DynamoQuery entityQuery)
{
results = new DynamoResult<Entity>();
try {
results = await GetPagedQueryResults(entityQuery);
}
catch (Exception e) {
Console.WriteLine(e);
}
return new DynamoResult<EntityResponse>
{
Data = results.Data.Select(_mapper.Map<EntityResponse>).ToList(),
};
}
Service 2:
private async Task<DynamoResult<TResponse>> GetPagedQueryResults(DynamoQuery query)
{
var results = new List<Document>();
try{
results = await search.GetNextSetAsync();
}
catch(Exception e){
throw new PaginationTokenException(e.Message);
}
return results;
}
[Serializable]
public class PaginationTokenException : Exception
{
public PaginationTokenException() { }
public PaginationTokenException(string message)
: base(message) {
throw new Exception(message);
}
public PaginationTokenException(string message, Exception inner)
: base(message, inner) { }
}
Assuming you want to hide implementation details from the controller (i.e. you don't want the controller to know/care that it's DynamoDB), I would create a custom exception and throw that from Service1.
Service1 would look something like this:
public async Task<DynamoResult<EntityResponse>> ListByParams(DynamoQuery entityQuery)
{
results = new DynamoResult<Entity>();
try {
results = await GetPagedQueryResults(entityQuery);
}
catch (Exception e) {
throw new MyCustomException('My error message', e);
}
return new DynamoResult<EntityResponse>
{
Data = results.Data.Select(_mapper.Map<EntityResponse>).ToList(),
};
}
In the controller you can then capture that exception explicitly:
[HttpGet]
[Authorize(Policy = "Read-Entity")]
[Route("byParams/{param1}/{param2}")]
[Produces(typeof(DynamoResult<EntityResponse>))]
public async Task<IActionResult> ListByParams([FromQuery] DynamoQuery entityQuery)
{
try
{
return await HandleRequest(async () =>
{
return Ok((await _entityStore.ListByParams(entityQuery)));
});
}
catch (MyCustomException e)
{
return BadRequest(e.Message);
}
}
A good suggestion on how to handle errors within a Client can be found here.
Copying here for easy access:
MyServiceClient myServiceClient = new MyServiceClient();
try
{
documents = myServiceClient.GetDocuments();
// More code that isn't useful including here ...
myServiceClient.Close();
}
catch (TimeoutException exception)
{
MessageBox.Show(exception.Message, "Timeout error", MessageBoxButtons.OK, MessageBoxIcon.Error);
myServiceClient.Abort();
}
catch (FaultException<ServiceErrorDetails> error)
{
MessageBox.Show(error.Detail.Message, "Service error", MessageBoxButtons.OK, MessageBoxIcon.Error);
myServiceClient.Abort();
}
catch (CommunicationException exception)
{
MessageBox.Show(exception.Message, "Communication error", MessageBoxButtons.OK, MessageBoxIcon.Error);
myServiceClient.Abort();
}
Now the problem I am having with this solution is that my Proxy contains many many methods. Easy to understand I would rather not want to add this huge try/catch statement around all my method calls.
Instead, I thought it could be a good idea to add the error handling from within MyServiceClient() class.
But the question is how to do that without polluting all the Methods here again with this try/catch statement?
How would you approach that?
You could try encapsulating the try/catch logic in a handler class as follows:
public static class Example
{
public static void ExecuteExample()
{
var serviceClient = new ServiceClient();
var documents = ProxyErrorHandler.Execute(serviceClient, serviceClient.GetDocuments);
}
}
public static class ProxyErrorHandler
{
public static void Execute(ServiceClient serviceClient, Action actionToExecute)
{
Execute(serviceClient, () =>
{
actionToExecute();
return true;
});
}
public static T Execute<T>(ServiceClient serviceClient, Func<T> functionToExecute)
{
try
{
return functionToExecute();
}
catch (Exception exception)
{
ShowException(serviceClient, exception);
return default;
}
}
public static Task ExecuteAsync(ServiceClient serviceClient, Func<Task> actionToExecute)
{
return ExecuteAsync(serviceClient, async () =>
{
await actionToExecute();
return true;
});
}
public static async Task<T> ExecuteAsync<T>(ServiceClient serviceClient, Func<Task<T>> functionToExecute)
{
try
{
return await functionToExecute();
}
catch (Exception exception)
{
ShowException(serviceClient, exception);
return default;
}
}
private static void ShowException(ServiceClient serviceClient, Exception exception)
{
string title;
var message = exception.Message;
switch (exception)
{
case TimeoutException:
title = #"Timeout error";
break;
case FaultException<ServiceErrorDetails> faultException:
title = #"Service error";
message = faultException.Detail.Message;
break;
case CommunicationException:
title = #"Communication error";
break;
default:
ExceptionDispatchInfo.Throw(exception);
// Unreachable
throw new Exception();
}
MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
serviceClient.Abort();
}
}
In my project I'm calling a lot of WebApi with Refit (link). Basically, I define the WebApi as an interface. For example:
public interface ICustomer
{
[Get("/v1/customer")]
Task<CustomerResponse> GetDetails([Header("ApiKey")] string apikey,
[Header("Authorization")] string token,
[Header("Referer")] string referer);
}
For each WebApi, I create a client like that:
public async Task<CustomerResponse> GetDetails(string apikey, string token)
{
CustomerResponse rsl = new CustomerResponse();
rsl.Success = false;
var customer = RestService.For<ICustomer>(apiUrl);
try
{
rsl = await customer.GetDetails(apikey, token, apiUrl);
rsl.Success = true;
}
catch (ApiException ax)
{
rsl.ErrorMessage = ax.Message;
}
catch (Exception ex)
{
rsl.ErrorMessage = ex.Message;
}
return rsl;
}
The only difference between clients are the interface (in the above example code ICustomer), the return structure (in the example CustomerResponse derives from BaseResponse), and the function I have to call (in the example GetDetails with params).
I should have a base class to avoid duplicated code.
Thanks in advance.
I like when people gives you a negative feedback without any explanation or a solution. If someone has a similar problem of mine, it can find my generic class to resolve this problem.
public class BaseClient<T> where T : IGeneric
{
public const string apiUrl = "<yoururl>";
public T client;
public BaseClient() : base() {
client = RestService.For<T>(apiUrl);
}
public async Task<TResult> ExecFuncAsync<TResult>(Func<TResult> func)
where TResult : BaseResponse
{
TResult rsl = default(TResult);
T apikey = RestService.For<T>(apiUrl);
try
{
rsl = func.Invoke();
rsl.Success = true;
}
catch (ApiException ax)
{
rsl.ErrorMessage = ax.Message;
}
catch (Exception ex)
{
rsl.ErrorMessage = ex.Message;
}
return rsl;
}
public async Task<List<TResult>> ExecFuncListAsync<TResult>(Func<List<TResult>> func)
{
List<TResult> rsl = default(List<TResult>);
T apikey = RestService.For<T>(apiUrl);
try
{
rsl = func.Invoke();
}
catch (ApiException ax)
{
}
catch (Exception ex)
{
}
return rsl;
}
}
I have a wcf api and wish to wrap all requests inside a transaction
Currently my code looks like this in each endpoint
public MyCompleteList ReadOrganisations()
{
MyCompleteList resp = new MyCompleteList ();
try
{
using (TransactionScope scope = new TransactionScope())
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
DC_Base browser_request = new DC_Base(PROJECT);
browser_request.cmd_user_id = coreDb.GetUserIDFromLoginName(PROJECT,
HttpContext.Current.User.Identity.Name);
resp =
new MyCompleteList (coreSc.User_Read_All_Organisations(browser_request, utils,
validation, coreSc, coreDb));
scope.Complete();
}
else
{
resp.SetResponseNotLoggedIn();
}
}
}
catch (TransactionAbortedException ex)
{
resp.SetResponseServerError();
}
catch (ApplicationException ex)
{
resp.SetResponseServerError();
}
return resp;
}
As you can see if I am to use the "using" transaction scope part in every endpoint (approx 300) its going to be a lot of duplicated code.
is there anyway to reduce the amount of duplication?
You can write a helper method, that handles the transaction logic while calling your actual code as a lambda.
public static T Execute<T>(Func<T> func, TransactionExecutionOptions options = null)
{
options = options ?? TransactionExecutionOptions.Default;
T res;
using (var tx = new TransactionScope(options))
{
res = func();
tx.Complete();
}
return res;
}
Depending on your needs you can provide additional arguments to the Func argument; for example, the Execute method could also open a database connection and pass that to the func (then having Func<IDbConnection, T> as parameter type). YMMV.
For your example:
public MyCompleteList ReadOrganisations()
{
MyCompleteList resp = new MyCompleteList ();
try
{
resp = Execute(() => {
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
DC_Base browser_request = new DC_Base(PROJECT);
browser_request.cmd_user_id = coreDb.GetUserIDFromLoginName(PROJECT,
HttpContext.Current.User.Identity.Name);
resp =
new MyCompleteList (coreSc.User_Read_All_Organisations(browser_request, utils,
validation, coreSc, coreDb));
scope.Complete();
}
else
{
resp.SetResponseNotLoggedIn();
}
});
}
catch (TransactionAbortedException ex)
{
resp.SetResponseServerError();
}
catch (ApplicationException ex)
{
resp.SetResponseServerError();
}
return resp;
}
If possible, you can also factor the SetResponse*() methods out into a base class or interface (say IMyResponse), thus making it possible to handle this aspect inside the Execute method as well.
public static T Execute<T>(Func<T> func, TransactionExecutionOptions options = null) where T : IMyResponse
{
options = options ?? TransactionExecutionOptions.Default;
T res;
try
{
using (var tx = new TransactionScope(options))
{
res = func();
tx.Complete();
}
}
catch (TransactionAbortedException ex)
{
res.SetResponseServerError();
}
catch (ApplicationException ex)
{
res.SetResponseServerError();
}
return res;
}
1- Create a ServiceBase class as follows
public class ServiceBase
{
protected void ExecuteOperation(Action codetoExecute)
{
try
{
using (TransactionScope scope = new TransactionScope())
{
codetoExecute.Invoke();
scope.Complete();
}
}
catch (TransactionAbortedException ex)
{
// handle exception
}
catch (ApplicationException ex)
{
// handle exception
}
}
}
2- Each new service must inherits from ServiceBase and call ExecuteOperation instead. Code as follows:
ExecuteOperation(() =>
{
// Custom code here
});
3- Atomic transactions are useful when executing operations that dont expect results in return.
In Framework WebAPI 2, I have a controller that looks like this:
[Route("create-license/{licenseKey}")]
public async Task<LicenseDetails> CreateLicenseAsync(string licenseKey, CreateLicenseRequest license)
{
try
{
// ... controller-y stuff
return await _service.DoSomethingAsync(license).ConfigureAwait(false);
}
catch (Exception e)
{
_logger.Error(e);
const string msg = "Unable to PUT license creation request";
throw new HttpResponseException(HttpStatusCode.InternalServerError, msg);
}
}
Sure enough, I get back a 500 error with the message.
How can I do something similar in ASP.NET Core Web API?
HttpRequestException doesn't seem to exist. I would prefer to continue returning the object instead of HttpRequestMessage.
What about something like this. Create a middleware where you will expose certain exception messages:
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
context.Response.ContentType = "text/plain";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
if (ex is ApplicationException)
{
await context.Response.WriteAsync(ex.Message);
}
}
}
}
Use it in your app:
app.UseMiddleware<ExceptionMiddleware>();
app.UseMvc();
And then in your action throw the exception:
[Route("create-license/{licenseKey}")]
public async Task<LicenseDetails> CreateLicenseAsync(string licenseKey, CreateLicenseRequest license)
{
try
{
// ... controller-y stuff
return await _service.DoSomethingAsync(license).ConfigureAwait(false);
}
catch (Exception e)
{
_logger.Error(e);
const string msg = "Unable to PUT license creation request";
throw new ApplicationException(msg);
}
}
A better approach is to return an IActionResult. That way you dont have to throw an exception around. Like this:
[Route("create-license/{licenseKey}")]
public async Task<IActionResult> CreateLicenseAsync(string licenseKey, CreateLicenseRequest license)
{
try
{
// ... controller-y stuff
return Ok(await _service.DoSomethingAsync(license).ConfigureAwait(false));
}
catch (Exception e)
{
_logger.Error(e);
const string msg = "Unable to PUT license creation request";
return StatusCode((int)HttpStatusCode.InternalServerError, msg)
}
}
It's better not to catch all exceptions in every action. Just catch exceptions you need to react specifically and catch (and wrap to HttpResponse) all the rest in Middleware.