Matthew Flynn
Matthew Flynn

Reputation: 3941

using filter to handle errors mvc c#

I have numerous method which I call using jquery ajax.

In order to handle any errors in the fail method I use the following code;

    public async Task<ActionResult> UpdateStockTransactionAsync(
        string TransactionDate, string Quantity, string ProductId, string TabCount)
    {
        try
        {
            //my code goes here

        }
        catch (System.Web.Http.HttpResponseException ex)
        {
            var msg = ex.Response.Content.ReadAsStringAsync().Result;
            var errorModel = JsonConvert.DeserializeObject<AcknowledgementModel>(msg);
            return new HttpStatusCodeResult(500, errorModel.errormessage);
        }
        catch (Exception ex)
        {
            return new HttpStatusCodeResult(500, ex.Message);
        }
    }

I seem to be repeating this an awful lot throughout my code, is it possible to maybe pull this out to a filter attribute? if so how?

Upvotes: 1

Views: 1135

Answers (1)

Perfect28
Perfect28

Reputation: 11327

One option is to use the overridable method OnException available on Controller class.

protected override void OnException(ExceptionContext filterContext)
{
    var exception = filterContext.Exception;

    if (exception is System.Web.Http.HttpResponseException) // Catch HttpResponseException
    { 
        var msg = ex.Response.Content.ReadAsStringAsync().Result;
        var errorModel = JsonConvert.DeserializeObject<AcknowledgementModel>(msg);
        filterContext.Result =  new HttpStatusCodeResult(500, errorModel.errormessage);
    }
    else // catch (Exception ex)
    {
        filterContext.Result = new HttpStatusCodeResult(500, ex.Message);
    }

    base.OnException(filterContext); 
}

You can redirect results with filterContext.Result

Upvotes: 2

Related Questions