简体   繁体   中英

C# using db context and exception handling in a better way (DRY)

I am writing this piece of code in the given action of WEP API controller in all my action methods in web API controllers I am making resulting in a lot of code redundancy and repeating my self (!DRY) hence i need a way this can be done with a better approach using inheritance or iterface or by using any other object oriented approach.

[Route("myApiGetRequest")]
[HttpGet]
public IHttpActionResult myApiGetRequest(long id)
{
    try
    {
        DataTable transaction = new DataTable();
        using (var context = new myDbContext())
        {
            //code for what I want to do

        }
    }
    catch (Exception ex)
    {
        return Ok(new { success = false, message = ex.Message });
    }
}

ExceptionHandling can be done by implementing your own ExceptionFilterAttribute . You can use this attribute to decorate all controllers which need an exception handling.

Basiclly, you override the OnException method and convert different exception types into status code and message.

You can take advantage of exception filters which are available in WebApi . Then, move exception handling code to that filter.

For instance:

public class MyExceptionFilterAttribute : ExceptionFilterAttribute 
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is Exception)
        {
            context.Response = new HttpResponseMessage { Content = new StringContent("Exception occured", System.Text.Encoding.UTF8, "text/plain"), StatusCode = HttpStatusCode.InternalServerError};
        }
    }
}

And then in your WebApi controller you can do following:

[Route("myApiGetRequest")]
[HttpGet]
[MyExceptionFilter]
public IHttpActionResult myApiGetRequest(long id)
{
    DataTable transaction = new DataTable();
    using (var context = new myDbContext())
    {
         //code for what I want to do

    }
}

Exceptions which then will occur in your myApiGetRequest will be handled by corresponding exception filter which this method is decorated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM