How to report error to $.ajax without throwing exception in MVC controller?

前端 未结 7 555
天涯浪人
天涯浪人 2020-12-14 06:53

I have a controller, and a method as defined...

[HttpPost]
public ActionResult UpdateUser(UserInformation model){

   // Instead of throwing exception
   thr         


        
相关标签:
7条回答
  • 2020-12-14 07:31

    You can create a helper method in a base controller that will return an server error but with your custom status code. Example:

    public abstract class MyBaseController : Controller
    {
        public EmptyResult ExecutionError(string message)
        {
            Response.StatusCode = 550;
            Response.Write(message);
            return new EmptyResult();
        }
    }
    

    You will call this method in your actions when needed. In your example:

    [HttpPost]
    public ActionResult UpdateUser(UserInformation model){
    
       // Instead of throwing exception
       // throw new InvalidOperationException("Something went wrong");
    
    
       // The thing you need is 
       return ExecutionError("Error Message");
    
       // which should be received as an error to my 
       // $.ajax at client side...
    
    }
    

    The errors (including the custom code '550') can be handled globally on client side like this:

    $(document).ready(function () {
        $.ajaxSetup({
            error: function (x, e) {
                if (x.status == 0) {
                    alert('You are offline!!\n Please Check Your Network.');
                } else if (x.status == 404) {
                    alert('Requested URL not found.');
    /*------>*/ } else if (x.status == 550) { // <----- THIS IS MY CUSTOM ERROR CODE
                    alert(x.responseText);
                } else if (x.status == 500) {
                    alert('Internel Server Error.');
                } else if (e == 'parsererror') {
                    alert('Error.\nParsing JSON Request failed.');
                } else if (e == 'timeout') {
                    alert('Request Time out.');
                } else {
                    alert('Unknow Error.\n' + x.responseText);
                }
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题