ERPNext Foundation ERPNext Cloud User Manual Blog Discuss Frappé* Donate

How to handle validation/Exception Error? if user request to "Cancel document" which is already cancelled

customization

#1

Hi to all,

I am just trying to handle exceptions if user will give request to cancel doc which is already cancelled then system generate an error

      File "/home/frappe/frappe-bench/apps/frappe/frappe/model/document.py", line 635, in check_if_latest
    self.check_docstatus_transition(tmp.docstatus)
  File "/home/frappe/frappe-bench/apps/frappe/frappe/model/document.py", line 677, in check_docstatus_transition
    raise frappe.ValidationError(_("Cannot edit cancelled document"))
ValidationError: Cannot edit cancelled document

my code is

@frappe.whitelist()
def cancelEntry(name):
	doc = frappe.get_doc('DocType', name) 
	doc.docstatus=2
	doc.save()	

now, i want the script that able to catch the exception and show error popup message to user?


#2

No one here to guide me about this issue


#3

any answer for this question?


#4

This is more of a python than erpnexr question but ok.

You can use try and except construct available in Python:

@frappe.whitelist()
def cancelEntry(name):
    try:
	    doc = frappe.get_doc('DocType', name) 
	    doc.docstatus=2
	    doc.save()
    except ValidationError as exc:
        frappe.throw("You cannot cancel a document more than once")

#5

I already tried it on “Stock Entry” and it shows the exception error in popup
but now problem is that it also gets cancelled “Stock Entry” in background
but it should not cancel the stock entry with try except block.


#6

Well, then why not filter the doctype by getting only those that not cancelled.

@frappe.whitelist()
def cancelEntry(name):
	doc = frappe.get_doc('DocType', {'name': name,'docstatus':('<', 2)}) 
	if(doc):
        doc.docstatus=2
      	doc.save()
    else:
        frappe.throw("No such un-cancelled document")

Does this work for you ?


#7

Thanks a lot.
This works for me.


#8

I’ve made a mistake. Dont filter by docstatus less than 2 but rather by docstatus = 1, because draft entries cannot be cancelled. Hence the correct scrip would be:

@frappe.whitelist()
def cancelEntry(name):
	doc = frappe.get_doc('DocType', {'name': name,'docstatus':1}) 
	if(doc):
        doc.docstatus=2
      	doc.save()
    else:
        frappe.throw("No such un-cancelled document")

#9

Thanks again.


#10

one more thing to ask

frappe.throw(“message text”)
frappe.throw(_(“message text”))

what is the difference between above frappe.throw?


#11

No difference in throw functionality. Second text message will be translatable from what I know.