jQuery Ajax error handling, show custom exception messages

前端 未结 21 2726
滥情空心
滥情空心 2020-11-22 01:50

Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message?

For example, if I want to throw an exception on the server side v

21条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 02:32

    A general/reusable solution

    This answer is provided for future reference to all those that bump into this problem. Solution consists of two things:

    1. Custom exception ModelStateException that gets thrown when validation fails on the server (model state reports validation errors when we use data annotations and use strong typed controller action parameters)
    2. Custom controller action error filter HandleModelStateExceptionAttribute that catches custom exception and returns HTTP error status with model state error in the body

    This provides the optimal infrastructure for jQuery Ajax calls to use their full potential with success and error handlers.

    Client side code

    $.ajax({
        type: "POST",
        url: "some/url",
        success: function(data, status, xhr) {
            // handle success
        },
        error: function(xhr, status, error) {
            // handle error
        }
    });
    

    Server side code

    [HandleModelStateException]
    public ActionResult Create(User user)
    {
        if (!this.ModelState.IsValid)
        {
            throw new ModelStateException(this.ModelState);
        }
    
        // create new user because validation was successful
    }
    

    The whole problem is detailed in this blog post where you can find all the code to run this in your application.

提交回复
热议问题