We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
close icon

How to display custom error message on AJAX action failture

I.m trying to display an error message after an update error on the grid.  I'm using the RemoteSaveAdaptor and found some information on the forum on how to do this (https://www.syncfusion.com/kb/5170/how-to-display-custom-error-message-on-ajax-action-failture).  I set the event ActionFailure on the grid, but having a few issues.

To test out everything, I just throw an error (throw new Exception("TEST");) in the controller and the event was fired, but I cannot see any why to get the error message from the event.  If I use the responseText, I get the html from the error page and the statusText says "Internal Server Error".  Is there any way to get the text from the error that was thrown.

Secondly, it seems like the ajax call never completes.  The spinner is still shown and now of the button on the grid is clickable.  

The java script for the function is as follows:

    function grid_ShowFailure(args) {
        alert(args.error.responseText);
    }

Thanks


9 Replies

JK Jayaprakash Kamaraj Syncfusion Team April 21, 2016 10:39 AM UTC

Hi Eric,

Thanks for contacting Syncfusion support.

We are able to get the text from the error that was thrown using ActionFailure event. This event triggers for every grid action server failure event.

We were able to face the issue with waiting popup shown and CRUD operations not reverted when action fails at server side. So, we have logged the requirement as an issue and a support incident has been created under your account to track the status of this requirement. Please log on to our support website to check for further updates. 

https://www.syncfusion.com/account/login?ReturnUrl=/support/directtrac/incidents 

As of now, use the below workaround in order to handle this issue. In this workaround, we have used cancelEdit method to stop editing/adding. If waiting popup is displayed in your sample while any server sider action gets failed, we can hide waiting popup manually using hide method of ejWaitingPopUp. Please refer to the following code example, screenshot, help documents and sample.


@(Html.EJ().Grid<object>("FlatGrid")

         .Datasource(ds => ds.Json((IEnumerable<object>)ViewBag.dataSource).UpdateURL("/Grid/Update").InsertURL("/Grid/Insert").RemoveURL("/Grid/Delete").Adaptor(AdaptorType.RemoteSaveAdaptor))

        .AllowSorting()

        .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing(); })

            .ToolbarSettings(toolbar =>

            {

                toolbar.ShowToolbar().ToolbarItems(items =>

                {

                    items.AddTool(ToolBarItems.Add);

                    items.AddTool(ToolBarItems.Edit);

                    items.AddTool(ToolBarItems.Delete);

                    items.AddTool(ToolBarItems.Update);

                    items.AddTool(ToolBarItems.Cancel);

                });

            })

        .AllowPaging()

        .Columns(col =>

        {

            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(90).ValidationRules(v => v.AddRule("required", true).AddRule("number", true)).Add();

            col.Field("EmployeeID").HeaderText("Employee ID").TextAlign(TextAlign.Right).Width(90).ValidationRules(v => v.AddRule("required", true)).Add();

            col.Field("Freight").HeaderText("Freight").TextAlign(TextAlign.Right).Width(80).EditType(EditingType.Numeric).Format("{0:C}").Add();

            col.Field("ShipCity").HeaderText("ShipCity").Width(150).Add();

        })

        .ClientSideEvents(eve => { eve.ActionFailure("Failure"); })  

)


<script type="text/javascript">

    function Failure(args) {

        var popupObj = $("#FlatGrid").data("ejWaitingPopup");

        popupObj.hide();

        this.cancelEdit();

        var str = "";

        str = $(args.error.responseText).find('i').text();

        alert(str);

    }
</script>
GridController.cs

public ActionResult Update(EditableOrder value)

        {

            throw new Exception("TEST");

            OrderRepository.Update(value);

            var data = OrderRepository.GetAllRecords();

            return Json(data, JsonRequestBehavior.AllowGet);
        }






Help document for actionFailure: http://help.syncfusion.com/js/api/ejgrid#events:actionfailure

Help document for cancelEdit: http://help.syncfusion.com/js/api/ejgrid#methods:canceledit

Help document for waitingpopoup: http://help.syncfusion.com/js/api/ejwaitingpopup#methods:hide

Sample: http://www.syncfusion.com/downloads/support/forum/123776/ze/Sample118221-376676842


Regards,

Jayaprakash K.


AK Aman kumar May 12, 2023 06:20 AM UTC

Hi After doing same thing i am getting internal server error 500. how can i resolve after follow same approach for display error msg.



FS Farveen Sulthana Thameeztheen Basha Syncfusion Team May 15, 2023 01:01 PM UTC

Hi Aman kumar,


Greetings from Syncfusion.


We have discussed the same “How to return Custom message from Controller when CRUD action fails” in our Syncfusion knowledge Base. As discussed, Internal Server Error will be thrown when CRUD Actions fails. Upon continue from Exception, we have shown the Error message with args.error.StatusText or args.error.responseText using ActionFailure event of the Grid.


KB link:- https://support.syncfusion.com/kb/article/6608/how-to-return-custom-message-from-controller-when-crud-action-fails

API link:- https://help.syncfusion.com/api/js/ejgrid#events:actionfailure


Please share more details if you need any further assistance on it.


Regards,

Farveen sulthana T



AK Aman kumar May 15, 2023 01:51 PM UTC

so when actionfailure will called and throw exception with error msg so by default it will throw internal server error if we not return status code with msg.



FS Farveen Sulthana Thameeztheen Basha Syncfusion Team May 16, 2023 04:15 PM UTC

Aman kumar,


Yes by default, it will show Internal Error if update action fails. You can show custom Error message if any Exception throws with ActionFailure event https://support.syncfusion.com/kb/article/4774/how-to-display-custom-error-message-on-ajax-action-failture


To be precis if the above solution doesn’t meet your requirement, share detailed explanation of your issue you faced to proceed further.


Regards,

Farveen sulthana T



AK Aman kumar May 19, 2023 09:41 AM UTC

so there is any way to Handle this internal error not showing in console. only popup open and display msg .



PS Pon Selva Jeganathan Syncfusion Team May 22, 2023 12:19 PM UTC

Hi Aman kumar,


Query: so there is any way to Handle this internal error not showing in console only popup open and display msg .


Based on your query, we understand that you prefer not to display error messages in the console, and you want to display an error message within a dialog. We achieved this requirement by using dialog component. In the actionFailure event, we prevent the console message, bind the error message into the dialog, and open the dialog to display the message.


Please refer to the below code example,


@{

 

    Html.EJ()

                  .Dialog("dialog")

                  .Title("Dialog")

                  .ShowOnInit(false)

 

                  .Render(); }

 

 

@(Html.EJ().Grid<Object>

    ("FlatGrid")

    .Datasource(http://mvc.syncfusion.com/Services/Northwnd.svc/Orders/)

    …..

    .ClientSideEvents(eve=>{eve.ActionFailure("FailMessage");})

    )

 

<script type="text/javascript">

        var str;

        function FailMessage(args) {

            console.clear();//clear the console

            var error =args.error.statusText;  //get the error message from server side.

            str = "<tr><td>" + error + "</td></tr>";

            $('#dialog').html("");

            $('#dialog').html("<table>" + str + "</table>");

            $("#dialog").ejDialog("open");

        }

    </script>

 


Please refer to the below screenshot,




Please refer to the below help documentation,

https://help.syncfusion.com/aspnetmvc/dialog/getting-started

https://stackoverflow.com/questions/42609230/how-do-i-handle-network-errors-so-they-dont-appear-in-chrome-developer-console


If the above solution does not meet your requirement, kindly share the below details which is helpful to proceed further.


  1. Complete Grid code example
  2. Detailed explanation of the requirement.
  3. Video demo / screenshot of the requirement


Kindly get back to us for further assistance.


Regards,

Pon selva


If this post is helpful, please consider Accepting it as the solution so that other members can locate it more quickly.




AK Aman kumar May 23, 2023 05:49 AM UTC

 function failure(args) {

        this.cancelEdit();

        var str = "";

        str = args.error.statusText;

       // str = $(args.error.responseText).find('i').text();

        $("#errorMsg").html(str).css("color", "Red");

        $("#actionFailureDialog").ejDialog("open");

    }

    $('#actionFailureCompleted').click(function () {

        $("#actionFailureDialog").ejDialog("close");

       

    })



 public ActionResult CommandUpdate(order value)

        {

            if (!ModelState.IsValid)

            {

                var errors = (from m in ModelState.Values

                              where m.Errors.Count > 0

                              select m).ToList();

                var errormsg = "";

                if (errors.Count > 0)

                {

                    for (int i = 0; i < errors.Count; i++)

                    {

                        errormsg = errors[i].Errors[0].ErrorMessage;


                    }


                }


                //throw new Exception(errormsg);

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, errormsg);





            }



i am using this when add or edit fail then i am able to display msg in dialog but i am also getting in console error msg.i want not show error msg in console when i am display msg through dialog. now i am getting error msg in console .



PS Pon Selva Jeganathan Syncfusion Team May 24, 2023 03:59 PM UTC

Aman kumar,


Query: i am using this when add or edit fail then i am able to display msg in dialog but i am also getting in console error msg.i want not show error msg in console when i am display msg through dialog. now i am getting error msg in console .


Based on your query, we understand that you want to prevent error messages from being displayed in the console when you show a message through a dialog. By default, any internal errors are shown in the console. To prevent this, you can use the console.clear() method to clear the console and prevent the error message from being displayed.


Please refer to the below code example,


@(Html.EJ().Grid<Object>

    ("FlatGrid")

    .Datasource(http://mvc.syncfusion.com/Services/Northwnd.svc/Orders/)

……

    .ClientSideEvents(eve=>{eve.ActionFailure("FailMessage");})

    )

    <script type="text/javascript">

        var str;

        function FailMessage(args) {

            console.clear();//clear the console

                   }


Please refer to the below help documentation,

https://stackoverflow.com/questions/42609230/how-do-i-handle-network-errors-so-they-dont-appear-in-chrome-developer-console


If the above solution does not meet your requirement, kindly share the below details which is helpful to proceed further.


  1. Complete Grid code example
  2. Detailed explanation of the requirement.
  3. Video demo / screenshot of the requirement


Kindly get back to us for further assistance.


Regards,

Pon selva


If this post is helpful, please consider Accepting it as the solution so that other members can locate it more quickly.




Loader.
Live Chat Icon For mobile
Up arrow icon