Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...