What is the best & easiest way for Exception Handling via AJAX in MVC?

别来无恙 提交于 2019-12-25 07:59:41

问题


I have an MVC5 project and need to handle exceptions by using a custom method that can be used for all of the Controller or Action methods. For solving the problem I have found some example as posted on Exception handling in ASP.NET MVC and tried to use follow an approach as shown below:

Custom Attribute:

public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        filterContext.ExceptionHandled = true;
        filterContext.Result = new JsonResult
        {
            Data = new { success = false, error = filterContext.Exception.ToString() },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
}

Controller:

[MyErrorHandler]
public ActionResult Delete(int id)
{
    Course deletedCourse = repository.DeleteCourse(id);             
    if (deletedCourse == null)
    {
        throw new Exception("Error...");
    }
}

View:

$.ajax({

    //code omitted for brevity

    success: function (result, textStatus, XMLHttpRequest) {
        if (!result.success) {
            alert(result.error);
        }
    }
});

Although this approach is working properly, there is not enough information in filterContext to return to the View as an meaningful message or exception type i.e. "database constraint error, etc." So, is there any better approach having a detailed information regarding to exception and using JSON as in this example.


回答1:


For meaningful exception you must make a custom exception or new exception with custom message like

//In DAL layer
     try
        {
            // do your insert
        }
        catch (SqlException ex)
        {

            if (ex.Number == 2627) // <-- but this will
            {
              throw new Exception("Your Custom mesage",ex);
                //Violation of primary key. Handle Exception
            }
        }

you must throw your exception and in Web layer get your exception with custom message.you can show your custom message to user and log original exception message for developers.




回答2:


ExceptionContext.Exception will contain the thrown exception, if there is not enough information in that, then it could be because you are not providing it (based on the example code, only the exception message is provided).

Handling all exceptions in an application-level filter sounds great until you have special cases that you need to address. Not all errors are created equal. Exceptions are also expensive, it may be better to consider sending meaningful error objects back from the controller action, with an appropriate HTTP Response Code identifying the issue.

I'm sure you're already aware but surfacing full exception messages, call stacks, etc to the browser may not be wise as it can reveal the design and structure of your application, possibly allowing an attacker to identify a vulnerability.

Sending raw exception data back provides the error to the person who is typically least able to do something about it: the user. I would strongly recommend logging the exception and then sending a meaningful message back to the user, but without potentially divulging sensitive information about your app.



来源:https://stackoverflow.com/questions/39601193/what-is-the-best-easiest-way-for-exception-handling-via-ajax-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!