openui5 icon indicating copy to clipboard operation
openui5 copied to clipboard

Can´t use sap.ui.model.odata.v4.Context.created() on 400 Error

Open marianfoo opened this issue 3 years ago • 11 comments

OpenUI5 version:

1.113.0

Browser/version (+device/version):

Chrome 113

Any other tested browsers/devices(OK/FAIL):

URL (minimal example if possible):

https://github.com/marianfoo/ODataV4Created

User/password (if required and possible - do not post any confidential information here):

Steps to reproduce the problem:

  1. git clone https://github.com/marianfoo/ODataV4Created
  2. npm i
  3. npm start
  4. press Button Create Fail

What is the expected result?

Promise is still pending

What happens instead?

Nothing happens and code crash. No "try catch" help here. Errors are displayed in the console: image

Any other information? (attach screenshot if possible)

I already asked here:https://answers.sap.com/questions/13886695/problem-with-odatav4context-and-created-promise.html

What I want to achieve:

  1. Create an array of payloads.
  2. Wait until Create succeeds or fails.
  3. If successful then activate the draft.
  4. On unsuccessful reset the context or the changes.

As you can see in the comments i already tried with the event CreateCompleted or ´hasPendingChanges´. In both instances i can tell if there is an error but both say the the batch request is still pending. How can i tell the batch request is finished?

I would be really an easy solution to just reject the context.created() promise. Why isn´t this happening here?

Thanks for your help!

marianfoo avatar May 18 '23 12:05 marianfoo

Hello @marianfoo ,

Thank you for sharing this finding. I've created an internal incident 2370076626. The status of the issue will be updated here in GitHub.

Regards, Petar

dimovpetar avatar May 18 '23 14:05 dimovpetar

Hello @marianfoo , I'm not sure if I understood your problem correct...

If you want cancel the creation request, you can use the #delete function of the context, if you delete the context also the request should be canceled...

Does this help to solve your problem?

Best regards Alex

alexanderriess avatar May 19 '23 13:05 alexanderriess

Hi @alexanderriess thanks for your reply.

I try to properly handle errors from backend. I can´t use context.created() because on error i can´t catch this promise. So my workaround(?) is to use attachCreateCompleted to wait for completion. I need to know when everything is finished to activate the draft right after the creation via code. I just don´t find good code examples to handle errors.

I just tried it now with this code:

        const tableObject = this.byId('createactivate::OrdersList--fe::table::Orders::LineItem-innerTable');
        const binding = tableObject.getBinding('items');
        const model = tableObject.getModel();

        let resolveFunction;
        let rejectFunction;
        const promise = new Promise((resolve, reject) => {
            resolveFunction = resolve;
            rejectFunction = reject;
        });
        binding.attachCreateCompleted(oEvent => {
            let { context, success } = oEvent.getParameters();
            if (!success) {
              console.log("failed")
              console.log(context)
              context.delete();
              rejectFunction(context);
            }
            else {
                resolveFunction(context);
            }
          }, this);

        const contexts = [];
        try {
          for (let index = 0; index < payloads.length; index++) {
            const element = payloads[index];
            const context = binding.create(element, true);
            contexts.push(context);
          }
          binding.getModel().submitBatch(model.getUpdateGroupId());
        } catch (error) {
          console.log('error while creating');
        }
        // will crash on error
        //await Promise.all(contexts.map(context => context.created()));

I this example created() is used also like i would expect. What is good practice here?

I hope this gives you a better undertanding.

Cheers

marianfoo avatar May 20 '23 18:05 marianfoo

Hello @marianfoo , We now have a far better understanding of your problem, we think you can solve your issue if you are using the promise returned by our #submitBatch function. After this promise is resolved you can check for pending changes, or you can ask the message model for the detailed error message.

I hope this helps you to solve your issue, if not feel free to reopen this case or ask us directly.

Best regards Alex

alexanderriess avatar May 30 '23 05:05 alexanderriess

Hi @alexanderriess, thank you for your direct help so far. This has already helped me a lot. I still have one question: After I have determined with "hasPendingChanges()" that there are incorrect creations, I want to delete the individual context with "delete()". Direct deletion is not possible, because I get the error "Error: No 'delete' allowed while waiting for server response". Currently I would take the event "createCompleted" from the List Binding and delete the context from the event parameter. Would that be correct or is there a other/better way/event to do it? Here is my current code so far:

        binding.attachCreateCompleted((oEvent) => {
          let { context, success } = oEvent.getParameters();
          if (!success) {
            // successfully deleted context
            context.delete();
          }
        });
        let contexts = [];
        for (let index = 0; index < payloads.length; index++) {
          const element = payloads[index];
          const context = binding.create(element, true);
          contexts.push(context);
          context.created().catch((error) => {
            console.log('error while creating context.created().catch(');
          });
        }
        await binding.getModel().submitBatch(model.getUpdateGroupId());
        if (!binding.hasPendingChanges()) {
          console.log('success');
        } else {
          console.log('hasPendingChanges() true');
          // batch request is still running, cant reset changes here
          contexts.forEach(async (context) => {
            await context.delete(model.getUpdateGroupId());
          });
          // cant use resetChanges because just want to delete contexts create above
          //model.resetChanges(model.getUpdateGroupId());
          // show message model
          // delete all messages after close
        }

This error appears when i try to delete the context with

console.log('hasPendingChanges() true');
// batch request is still running, cant reset changes here
contexts.forEach(async (context) => {
    await context.delete(model.getUpdateGroupId());
});

image

Here is the complete Javascript Code: https://github.com/marianfoo/ODataV4Created/blob/main/webapp/ext/Create.js

marianfoo avatar May 30 '23 09:05 marianfoo

Hi @marianfoo, I tried to reproduce your issue, but it was not possible...

Until I changed the updateGroupId to $auto, is it possible that you have not declared an updateGroupId?

In the case of using $auto the model tries immediately to sent the POST request again... So the Error you see, occurs because the request is already queued again. In that case we can not delete the context...

I would suggest to use a specific updateGroupId, so you can be sure that you have the full control about sending and receiving batches. And you can be sure that no one other has added a request to your batch...

I hopes this helps you to solve your Issue, if not feel free to contact us again...

Best regards Alex

alexanderriess avatar May 30 '23 16:05 alexanderriess

Hi @alexanderriess you are right. With an updateGroupId I could delete the context. But since I have no control over the binding and the configuration of the OData service, I created my own ListBinding to execute create with it.

this.customBinding = binding.getModel().bindList(binding.getPath(),null,[],[],{$$updateGroupId: "create"});

Any comments on that way?

marianfoo avatar May 31 '23 07:05 marianfoo

Hi @marianfoo , From our perspective this looks good and could be helpful! Maybe some remarks:

  • the #getPath function does not deliver in every case an absolute Path, maybe it would be better to use #getResolvedPath
  • The name of the updateGroup is maybe not safe enough to prevent, that other could use it? Maybe you have a unique Package Name? Or if you want totally safe you can use a GUID?

Have you thought about filters, sorters or other custom query options? Seems to be unrealistic? What do you think?

alexanderriess avatar May 31 '23 16:05 alexanderriess

Hi @alexanderriess Both good suggestions. A guid would actually work, because every request is a single instance and I don't need it again.

What do you mean with filters and sorters? Why would I need this?

marianfoo avatar May 31 '23 17:05 marianfoo

The only thing I could imagine is that it could be necessary to sort the data bevor sending it? But in your case it would also be possible in the excel sheet... So maybe this is not needed... Was only an idea....

alexanderriess avatar May 31 '23 17:05 alexanderriess

Okay, i thought more of a technical reason. But you're right, i just take the data from Excel as it is. I could introduce this as an option, but I don't see any need for it now. Thank you for all your help! See you in July.

marianfoo avatar May 31 '23 17:05 marianfoo