cancel
Showing results for 
Search instead for 
Did you mean: 

CAP JAVA: Throw ServiceException without database rollback

christoffer_fuss
Participant
0 Kudos

Hello,

I have a custom event handler which updates some database tables. If there occurs any error I use the ServiceException class to pass the error to the user. But then all the database changes are rollbacked.

 throw new ServiceException(ErrorStatuses.FORBIDDEN, messages.error("CONSENT_CONTRACT_TO_MANY_ATTEMPS").getMessage());
  

Is there a way to keep the database changes and still pass the error to the user?

If I use the message class without the exception the statusCode is not set to 400 and the message ust occurs in the response header.

Best regards,
Chris

Accepted Solutions (1)

Accepted Solutions (1)

marcbecker
Contributor
0 Kudos

Hi Chris,

I'd recommend to run the database interactions in a dedicated changeset, which you can fully control. In that changeset you can avoid that the exception causes a rollback and propagate the exception to the client outside of the changeset. Here is how that could look like:

Exception error = runtime.changeSetContext().run(changeSet -> {
  try {
    db.run(...) // do your database interactions here..
    return null; // no error
  } catch (Exception e) { // could also catch only specific exceptions
    return e; // return error
  }
}); // transaction is committed here
if (error != null) {
  throw error; // propagate error to client
}

Best regards,
Marc

christoffer_fuss
Participant
0 Kudos

Hi Mark,

thanks for your help. This sounds good but If I try your code I get this exception: "Failed to start a new transaction".
I run this code on localhost with sqlite db in a custom function handler.
Do you have an idea why this happens?

Best regards and many thanks,
Chris

marcbecker
Contributor
0 Kudos

SQLite has some issues with parallel transactions, which is why usually the connections are limited to exactly one. This means that you can't create a nested transaction. I'd recommend to rather switch your local tests to a database that supports such scenarios better. CAP Java meanwhile propagates usage of H2 over SQLite. You can find details about the different databases here: https://cap.cloud.sap/docs/java/persistence-services#h2

christoffer_fuss
Participant
0 Kudos

Thanks Marc,
on HANA DB the code is working fine :). We will try to switch to H2 on locolhost.
Best Regards,

Chris

Answers (0)