0

I created a custom exception handling method as shown below and I can catch the database constraint exception with it and return the error to error method of AJAX call. However, when trying to create an exception using throw new Exception()" or throw new ArgumentNullException("instance") I encounter an error as displayed on the image below. Is there any mistake in the custom method? Or how can I test properly test it if it works for AJAX request and Normal request? Any help would be appreciated...

public class CustomErrorHandler : HandleErrorAttribute
{        
    public override void OnException(ExceptionContext filterContext)
    {
        //If the request is AJAX return JSON, else return View
        if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
        {
            // Log exception first
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            filterContext.Result = new JsonResult
            {
                Data = new
                {
                    success = false,
                    message = "Error occured",
                    type = filterContext.Exception.GetType().Name,
                    exception = filterContext.Exception.ToString(),
                    number = ((System.Data.SqlClient.SqlException)filterContext.Exception.InnerException.InnerException).Number
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };

            // Let the system know that the exception has been handled
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
        }
        else
        {
            // Normal Exception. So, let it handle by its default ways
            base.OnException(filterContext);
        }
    }
}

enter image description here

Jack
  • 1
  • 21
  • 118
  • 236
  • 1
    Most likely `filterContext.Exception.InnerException.InnerException` causes an NRE. http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – kiziu Sep 23 '16 at 09:04
  • @kiziu Yes, perfect!.. On the other hand, is there any mistake regarding to this custom method so that it can be used for catching exception for AJAX request and Normal request? I created this method by combining some approach as on http://stackoverflow.com/questions/4707755/asp-net-mvc-ajax-error-handling and http://www.codeproject.com/Articles/731913/Exception-Handling-in-MVC. Is there any mistake? – Jack Sep 23 '16 at 09:10
  • 1
    Biggest mistake I see is assuming that the exception is of any type without checking it first or using at least `as` operator - lack of checking will cause `InvalidCastException`. Using `IsAjaxRequest` is OK, assuming your JS code sets the required header in the request (I read that most frameworks do, eg. jQuery.ajax). How you handle the exception is entirely up to you. I would also consider changing the code to make it more readable, eg. http://stackoverflow.com/questions/268132/invert-if-statement-to-reduce-nesting – kiziu Sep 23 '16 at 09:14
  • @kiziu Many thanks for your help. Could you please post an answer by updating my code? On the other hand, I need a number regarding to the error type in order to identify the error specific. For example type parameter is "DbUpdateException", but I am not sure if this has a specific meaning. Because my exception is related to constraing and I need a specific errror number. How can I obtain it? There is a parameter called HResult and value of "-2146233087" but I am not sure if it identical to the error. – Jack Sep 23 '16 at 09:21
  • I'm sorry, my policy is to avoid fixing someone's code directly, I assume that they will learn more by fixing it themselves with guidance provided. As for the `Exception`s, you just have to write a custom handler for them, its body will only depend on the information you want to extract from them - I cannot help you with that because I don't know your goal. Just be sure to always check the their types and check for `null`s. – kiziu Sep 23 '16 at 09:28
  • Ok, in that case I should check **filterContext.Exception** value if it is null, is that true? Regrding to the other issue, I want to display the error message regarding to the origin of the exception, and for doing this I need a specific number belonging to the exception (I display message by switch of if clause using this exception number). Is that possible? – Jack Sep 23 '16 at 09:31
  • Checking `filterContext.Exception` for `null` seems a little redundant - since you already are in the exception handler, this property should not be `null`, but you can always check it if you want. In your case `null` checks should be used in at least 2 cases - checking `InnerException` before using it and checking the result of `as` operator when casting. As for the handling of specific `Exception`, I think it is beyond the scope of this question. – kiziu Sep 23 '16 at 09:37
  • I removed the number line and there is no need to check the InnerException. But I could not understand what do you mean by "**checking the result of as operator when casting**". Could you please explain a little bit more? On the other hand, why do you avoid to explain by posting the sample code so that a more brief and easy explanations? Thanks... – Jack Sep 23 '16 at 09:42
  • http://stackoverflow.com/questions/132445/direct-casting-vs-as-operator – kiziu Sep 23 '16 at 09:43
  • Do you mean casting of **(System.Data.SqlClient.SqlException)filterContext.Exception.InnerException.InnerException**? Is there another line to be casted as this? – Jack Sep 23 '16 at 09:46
  • @kiziu Any reply please??? – Jack Oct 04 '16 at 12:46

0 Answers0