Get response from server on Grid add/delete error.

Hello,

While adding/deleting a row from a Grid, I would like to access the response that server returns for that action.
For example, I want to perform some backend tests before allowing the addition of a new entry. If that entry is not allowed, a message will be sent as a response to the request with explanation on why it was not allowed.
I have set up the response in my backend but I have not found any way to fetch it in my frontend so that I can display it to the user,
For my Grid I'm using DataManager with UrlAdaptor like so:

const gridDataManager = new DataManager({
adaptor: new UrlAdaptor(),
insertUrl: 'test/insert',
removeUrl: 'test/remove',
url: 'test/index'
});

I have tried using Grid's property actionFailure which does not trigger even though the backend returns status: 400 or 500, and actionComplete which does have the response data in "promise" property, but to my understanding there is no way to parse them from there.

Is there some Grid property I'm missing or a DataManager/UrlAdaptor one for managing server's response?

Thank you in advance!
Best regards.

14 Replies 1 reply marked as answer

PG Praveenkumar Gajendiran Syncfusion Team June 1, 2021 01:32 PM UTC

Hi Spyros, 
Thanks for contacting Syncfusion support. 

We have validated your requirement and the ‘actionFailure’ event will be triggered when thrown the proper exception from the server/service.  

For your reference we have manually throw the exception in delete method and it will trigger the actionFailure event. Please refer the below code example, sample for more information. 

public void Remove([FromBody]CRUDModel<OrdersDetails> Value) 
        { 
            if (Value.KeyColumn == "OrderID") 
           { 
                throw new Exception("Value cannot be deleted"); 
            }//created exception 
            var data = orders.Where(or => or.OrderID.Equals(Value.Key)).FirstOrDefault(); 
            orders.Remove(data); 
        }         

actionFailure(args) { 
        console.log(args.error[0].error.responseText.split("Exception:")[1].split("</div>")[0]); 
    }  //get the error status 


Screenshot: 
 
 
Still, if you are facing any issue could you please share the full code example of Grid rendering and server-side handling for proceed further. 

Please get back to us if you need further assistance.

Regards,
Praveenkumar G 



SP Spyros June 1, 2021 01:44 PM UTC

Dear Praveenkumar Gajendiran,

Thank you for your reply and the example code!
I do know that throwing an exception in the server will result in request failure and will trigger the actionFailure event.
I don't think that's an ideal solution though, because all the API endpoints have to be changed to throw exceptions instead of just returning a response with the error that occurred like expected for an API.
The expected behavior is for Grid/DataManager/UrlAdaptor to be able to read server's response to the edit/add request, evaluate its http status (400-500) and show the error message that is attached in the request's response.
Is there a way to parse that information? Thank you!

Best regards!


PG Praveenkumar Gajendiran Syncfusion Team June 2, 2021 01:22 PM UTC

Hi Spyros,

Thanks for your update.

Based on your query, we would like to inform you that, By default, if the HTTP request gets success on the server-side, we do not handle/throw any failure at the HTTP request success, once the HTTP request failed to achieve the desired results, we will call the HTTP failure method to throw the failure exception at this case.  
  
 Here we trigger the Grid’s actionFailure event because the HTTP request failed to achieve the desired results and the HTTP failure method throw’s the failure exception. 
  
 We could see that you wish to throw the failure exception at the HTTP call request success function, but we cannot handle/call any HTTP failure method in this case, and also here we cannot trigger the Grid’s actionFailure event because the HTTP request in the success state. 
  
 So we suggest you to use the CustomAdaptor feature to achieve your requirement. The Custom Adaptor allows you to create your own adaptor by extending the built-in adaptors. Using this you can override the ProcessResponse method(Response processing method-Triggers after data is returned from the server) to check the response data from the server. 
  
 More details on the Custom adaptor can be checked from the below help documentation link,  

Custom adaptor: https://ej2.syncfusion.com/react/documentation/grid/data-binding/#custom-adaptor

For binding the data properly in the Grid, please return it as result and count properties to set it in the Grid as demonstrated in the below code example. 
 public dataManager: DataManager = new DataManager({ 
         adaptor: new CustomUrlAdaptor, 
         insertUrl: "Home/Insert", 
         removeUrl: "Home/Delete", 
         updateUrl: "Home/Update", 
          url: "Home/DataSource" 
  }); 
    class CustomUrlAdaptor extends new UrlAdaptor {   
// here we are overriding the default processresponse method of the UrlAdaptor adaptor   
        processResponse() {  
             // here you can able to check the response  
            // calling base class processResponse function   
            var original = super.processResponse.apply(this, arguments);   
           // Data is returned in the below format to set it in the Grid properly while using UrlAdaptor, I  if your data as empty  you need to send result as [] and count as 0  
 
                return { result: original.result, count: original.count }; 
 
        }   
    }   
   

Please get back to us if you need further assistance.
 
Regards,
Praveenkumar G 



SP Spyros June 4, 2021 04:00 PM UTC

Dear Praveenkumar G,

Thank you for your detailed reply, explanation and sample code!
I have been trying to implement it all day, but I could not manage to do so.

If I just console.log the response/error from within "processResponse", it works just fine, although I have not found any way to pass that information to the component that has the grid. Ideally I want to have React hook there that would trigger a notification/modal/etc showing the error. Although I'm using functional components in my application and I have not found any way to achieve that. I have checked most Grid's methods too but have not found any that would return the response of the customAdaptor in order to access it from there.

Finally, I have thought of a workaround involving invoking the processQuery method of the customAdaptor, but I have not found any documentation or indication on what response Grid and the rest of the adaptor functions need from it so that after accessing it's data I can return the awaited response for it to continue functioning properly.
Again, this last one is a workaround, so it would not be the ideal solution, but it will help me achieve what I need in this specific case.

If you can provide any hints on how to tackle these issues, I would really appreciate it!
Have a great day!

Best regards.


PG Praveenkumar Gajendiran Syncfusion Team June 7, 2021 12:58 PM UTC

Hi Spyros,

Thanks for your update. 
Before proceeding with query, we would like to inform you that processResponse is already a success response only, if you return it as result and count properties to the Grid as demonstrated in the below code example, the data will properly bind to the Grid.  
 public dataManager: DataManager = new DataManager({ 
         adaptor: new CustomUrlAdaptor, 
         insertUrl: "Home/Insert", 
         removeUrl: "Home/Delete", 
         updateUrl: "Home/Update", 
          url: "Home/DataSource" 
  }); 
    class CustomUrlAdaptor extends new UrlAdaptor {   
// here we are overriding the default processresponse method of the UrlAdaptor adaptor   
        processResponse() {  
             // here you can able to check the response  
            // calling base class processResponse function   
            var original = super.processResponse.apply(this, arguments);   
           // Data is returned in the below format to set it in the Grid properly while using UrlAdaptor 
                return { result: original.result, count: original.count }; 
 
        }   
    }   
   

So please
let us know, What you excepting at your end?, Do wish to notify the Grid when the response failed?  If not, please elaborate on your requirement with more details based on which we will check from our end and provide the further details.


For this “I have thought of a workaround involving invoking the processQuery method of the customAdaptor, but I have not found any documentation or indication on what response Grid and the rest of the adaptor functions need from it so that after accessing it's data I can return the awaited response for it to continue functioning properly.”

We would like to inform you that the processQuery(Request processing method) is used to generate and modify the request query which is sent to server. This is synchronies method, here we process the request query based on your action preformed in the Grid, so it does not wait for any other process.

So please let us know, why do you want this method as an async service, Please
elaborate on your requirement with more details based on which we will check from our end and provide the further details.

Regards,
Praveenkumar G




SP Spyros June 7, 2021 01:46 PM UTC

Dear Praveenkumar G,

I think that you have not understood my request, maybe I could have been more clear about it.
Let me walk you through one full scenario so that you can understand what I want to achieve:

I have a Syncfusion Grid on a React Functionable Component. I want to add a new entry to the grid. If the addition is done in my backend, my server responds with {"status":200,"message":"success"}.
That's great. Although if my backend decides that that new entry can't be added (ex. user has no rights to add this entry or it's a duplicate, etc), server responds with {"status":500,"message":"Entry could not be added for this and that reason"} and does not add the entry to the database.
In this case, grid will refresh and no new entries will be shown. Although there is no indication for the user to know what happened.
So, what I'm trying to achieve is to fetch that message reply from server, and display it to the user.

In my specific case, I use a packaged react modal to inform the user and I want to call its React hook and include the message from server's response as argument so that it'll be shown to the user.

By using "class CustomUrlAdaptor extends new UrlAdaptor" and overriding "processResponse()", I can console.log that server's message, but since I'm extending a class and overriding its methods, I can't use React hooks to call my react modal component and show the error message to the user. 

My request is how to achieve calling that hook that includes the server's message. It's more of a react/JS question than a Syncfusion one I think, but maybe you can help me with this, or provide some other solution on a way to fetch the server's response other than by extending UrlAdaptor, if my request can't be achieved with it.

If you need any further information please let me know.
Thank you once again!

Best regards.


PG Praveenkumar Gajendiran Syncfusion Team June 10, 2021 09:55 AM UTC

Hi Spyros,

Thanks for your update. 
We checked your query, based on that we would like to inform you that the Custom Adaptor feature allows you to create your own adaptor by extending the built-in adaptors, therefore here we cannot able to use/call react hooks function. Because react hooks are called only from React function components, it cannot be called from regular JavaScript functions, class ….

So please let us know, why do you want to call the react hooks function from the ProcessResponse method? why do you want to use the hooks function, to update the message in the Grid component or  any other specific component? and what do you wish to do with that status code?
 
Please share the above-requested details to validate further or your requirement.

Regards,
Praveenkumar G
 


Marked as answer

SP Spyros June 10, 2021 11:09 AM UTC

Dear Praveenkumar G,

Thank you for your reply and your willingness to help me with this.

> why do you want to use the hooks function, to update the message in the Grid component or  any other specific component?
The way I'm showing error messages to the user in the app is by rendering a toast notification, which is a React component (react-toast-notifications). So I want to call its hook with the error message as argument so that the toast notification will be displayed whenever there is an error in the grid add/edit/delete action.

> why do you want to call the react hooks function from the ProcessResponse method?
The only place I am aware of, where I can see the server's response to a grid add/edit/delete action is there, and because I need the server's response message in order to display it to the user, I'm trying to somehow call the react hooks function of the toast notifications component from that method.

> what do you wish to do with that status code?
I don't specifically need the status code for something, I only need the message. Although if I'm intercepting the ProcessResponse method, I need to have a way to know if the message is error or not, since I only need to display the toast notification only for errors and not for successful operations. A way to identify that is by the status code, for example in successful operations i can return status code 200 in the response, and status code 500 for the unsuccessful ones and have a condition that displays the toast notification only for those that have status code 500.

Best regards,
Spyros


SP Spyros June 10, 2021 11:21 AM UTC

UPDATE: After writing my last reply I went to investigate regarding the status code, because if it was 500 as I have had it set, request should not have had status 200 every time. Originally I thought that Grid was intercepting the request and after fetching server's response, it was setting the status to 200. But something was not adding up, so after a bit more search, I found out that server was not configured correctly and the status 500 that was returning was part of the response and not actually the status code of the request...
Once I fixed that, request's response was 500 as wanted in that case, and I could fetch the error message from actionFailure event of the Grid.

I'm very sorry for the inconvenience caused and I really appreciate the help you have provided which eventually led to me realizing that error in our backend.

Best regards,
Spyros


PG Praveenkumar Gajendiran Syncfusion Team June 11, 2021 09:45 AM UTC

Hi Spyros, 

Thanks for your update. We are glad that you have resolved the reported problem at your end. 
Please get back to us if you need further assistance. 

Regards, 
Praveenkumar G 




AK Aman kumar replied to Praveenkumar Gajendiran May 12, 2023 09:06 AM UTC

hi how can i handle internal server error when i throw exception msg. i am able to getting error msg but in console getting internal error. pls help 



RR Rajapandi Ravi Syncfusion Team May 18, 2023 11:59 AM UTC

Hi Aman,

Before we start providing solution to your query, we need some information for our clarification. So, please share the below details that will be helpful for us to provide better solution.


1)            Share your code example about how you are throwing the exception and how you are getting the error message.


2)            Share your package version.


3)            Share your complete Grid rendering code.


4)            Share your issue scenario in video demonstration, we would like to check at what case you are throwing the exception


Regards,

Rajapandi R



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

when insert or update fail then we throw exception msg and pass this msg to action failure method . then msg show in alert popup.


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

)

function
Failure(args) {

this.cancelEdit();


var
str =
"";


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


alert(str);

    }

public
ActionResult
Update(
EditableOrder
value)

        {


throw
new
Exception("TEST");


OrderRepository.Update(value);


var
data =
OrderRepository.GetAllRecords();


return
Json(data,
JsonRequestBehavior.AllowGet);
        }



FS Farveen Sulthana Thameeztheen Basha Syncfusion Team May 25, 2023 02:44 PM UTC

Hi Aman kumar,


Query: hi how can i handle internal server error when i throw exception msg. i am able to getting error msg but in console getting internal error


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,

Farveen sulthana T


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



Loader.
Up arrow icon