How to prevent from saving if other methods throw?

I have this feature to update field before_submit but then if there are any frappe throw that is out of my method it prevents from submit which is correct, but the field that I have update already saved. How am I able to stop the code from saving?

//
@frappe.whitelist()
def update_per_receive(data, field):
data = frappe.parse_json(data)

if isinstance(data, dict):
    data = [data]

for d in data:
    if d.get("is_cancelled") == 1:
        po_doc = frappe.get_doc("Purchase Order", d.get("document", ""))

        if d.get("pr_total_qty") == d.get("po_total_qty"):
            po_doc.set(field, 100)
        elif d.get("po_total_qty") > 0:
            po_doc.set(field, (d.get("pr_total_qty") / d.get("po_total_qty")) * 100)
        else:
            po_doc.set(field, 0)

        po_doc.save()

//

@Pejay you are calling this method from js manually ? you are creating a second object po_doc and it will not roll back if an error is thrown before submit .
consider using proper script using before_submit controller.

1 Like

Oh okay, I get it. let me try this on the controller. Thanks for advice @bahaou !