I use the code below to execute all methods from my WebApi controller. In the both webapi method, I invoke the code the same way but the returned type is different (CustomersResponse
and CustomerResponse
). The responses have the same base class (ResponseBase
). When no exception, no problem.
In case of exception I'd like get back a type ResponseBase
or create an instance of T
but be able to set Errors
, Warnings
and StatusCode
in the catch
of the exception.
How can I do this ?
Thanks,
public class ResponseBase
{
public ResponseBase()
{
StatusCode = HttpStatusCode.OK;
Errors = new List<string>();
Warnings = new List<string>();
}
public List<string> Errors { get; set; }
public List<string> Warnings { get; set; }
public HttpStatusCode StatusCode { get; set; }
}
public class CustomersResponse : ResponseBase
{
public List<string> Customers { get; set; }
}
//WebApi
[HttpPost]
[Route("list")]
public CustomersResponse List(CustomerRequest customerRequest)
{
return ExecuteCode<CustomersResponse>(() =>
{
return _customerFacade.List(customerRequest);
});
}
[HttpPost]
[Route("getbycode")]
public CustomerResponse GetByCode(CustomerRequest customerRequest)
{
return ExecuteCode<CustomerResponse>(() =>
{
return _customerFacade.GetByCode(customerRequest));
});
}
public T ExecuteCode<T>(Func<T> codeToExecute) where T : new()
{
var error = new T();
try
{
/*
doing some stuff here
*/
return codeToExecute.Invoke();
}
catch (Exception ex)
{
//Here I'd like return an ResponseBase object
//return error;
}
}
Aucun commentaire:
Enregistrer un commentaire