Wednesday, July 11, 2012

Reporting code errors when running code in SPLongOperation

As we all know, SPLongOperation is a great device to run a bit of code that takes a long time, while showing the user a turning cogwheel, and then redirecting when the operation is done.
However, when I checked, I saw people are on the search for a way to properly report on errors that happen during the long operation.
Some solutions involve redirecting to a new page, and passing the errors' details in the query string, or in some other way. Another way is to use the "EndScript" method to show a javascript "alert" (a messagebox, with the details.
I'd like to propose a different way. The page that is showing the cogwheel can be modified using the same javascript ("EndScript" method) by injecting html with the error details into the 's4-simple-card-content' div. This is critical if the page that is doing the long operation was opened as a dialog - in which case redirecting can be confusing, and we want to show the error if there was one, or close the dialog if there wasnt.

SPLongOperation longOp = new SPLongOperation(this.Page);
StringBuilder sbErrors = new StringBuilder();
throw new Exception("Sample");
catch(Exception ex)
  sbErrors.Append("An error occurred: " + ex.MEssage);

(sbErrors.Length > 0)
"document.getElementById('s4-simple-card-content').innerHTML = \"Errors have occurred during the submission. Details: " + sbErrors.ToString() + " \";");
//close the dialog if there were no errors


1 comment:

Colin Gardner said...

Really cool, just to let everyone know that if you are doing this in SharePoint 2013 the div with id 's4-simple-card-content' no longer exists use 'ms-loading-box' instead.