How to respond to SyntaxError in javascript

I get data from php server and sometimes it throws messages in warnings. These warnings lead to a parsing of the response to a syntax error that ignores all the try / catch code that I have and simply stops processing, leaving complex objects in partial states that cannot be recovered.

How can I catch these errors? I want to have a chance to return the object to a stable state.

Ideally, I would not get answers saying that I should rethink the architecture or change the php settings. I would like to know how to respond to SyntaxErrors, which is called by JSON.parse ().

Thanks Jeromeyers

EDIT:

I realized that the problem is more complicated than I originally thought. This is the code that SyntaxError does not catch:

generateSubmissionSuccessCallback: function (reloadOnSave) {
    var self = this;

    var submissionCallback = function(response) {
        var processingError = false;

        try
        {
            var responseObject = {};
            if (self.isAspMode())
            {
                if (typeof response !== 'object') // Chrome auto-parses application/json responses, IE & FF don't
                {
                    response = JSON.parse(response);
                }

                responseObject = {
                    entity: response.Payload,
                    success: response.Success,
                    message: response.Exception
                };

                if (jQuery.isArray(response.ValidationErrors))
                {
                    responseObject.message += ' \r\n\r\nValidation Errors\r\n';
                    for (var i = 0, maxi = response.ValidationErrors.length; i < maxi; i++)
                    {
                        var error = response.ValidationErrors[i];
                        responseObject.message += error.Error + '\r\n';
                    }
                }
            }
            else
            {
                responseObject = JSON.parse(response);
            }

            if (!responseObject || (responseObject.success !== undefined && responseObject.success !== true))
            {
                processingError = true;
                var message = responseObject ? responseObject.message : response;
                ErrorHandler.processError(
                    'An attempt to save failed with following message: \r\n' + message,
                    ErrorHandler.errorTypes.clientSide,
                    null,
                    jQuery.proxy(self.validatingAndSubmittingFinallyFunction, self));
            }
            else
            {
                // If this is a parent metaform, reload the entity, otherwise, close the metaform
                if (self.metaformType === 'details')
                {
                    if (self.substituteWhatToDoAfterSavingCallback)
                    {
                        self.substituteWhatToDoAfterSavingCallback(responseObject);
                    }
                    else if (reloadOnSave)
                    {
                        self.reloadCurrentEntity(true, responseObject.entity);
                    }

                    if (self.doesViewOutlineDefinePostSaveHook())
                    {
                        self.viewOutline.functions.postSaveHook(self);
                    }
                }
                else if (self.metaformType === 'childDetails')
                {
                    // Reload the Grid by which this form was made
                    if (self.associatedGridId)
                    {
                        Metagrid.refresh(self.associatedGridId);
                    }

                    if (self.parentMetaform.associatedGridId && self.childPropertyName)
                    {
                        var annotation = self.parentMetaform.getAnnotationByPropertyName(self.childPropertyName);
                        if (annotation && annotation.hasPropertyOptions('updateParentMetaformAssociatedGrid'))
                        {
                            Metagrid.refresh(self.parentMetaform.associatedGridId, self.parentMetaform.entityId);
                        }
                    }

                    if (self.substituteWhatToDoAfterSavingCallback)
                    {
                        if (self.doesViewOutlineDefinePostSaveHook())
                        {
                            self.viewOutline.functions.postSaveHook(self);
                        }

                        self.substituteWhatToDoAfterSavingCallback(responseObject);
                    }
                    else
                    {
                        if (self.doesViewOutlineDefinePostSaveHook())
                        {
                            self.viewOutline.functions.postSaveHook(self);
                        }

                        self.disposeMetaform();
                    }
                }
            }
        }
        catch (ex)
        {
            processingError = true;
            ErrorHandler.processError(
                "Please immediately inform the authorities that: \r\n\r\n" + typeof response === 'string' ? response : JSON.parse(response) + "\r\n\r\nand:\r\n\r\n " + ex.message,
                ErrorHandler.errorTypes.clientSide,
                null,
                jQuery.proxy(self.validatingAndSubmittingFinallyFunction, self));
        }
        finally
        {
            // If we are reporting an error to the user then we can't reset these state variables
            // because in the case where this is a child form, the parent will close the form
            // before the user has read the error.
            if (!processingError)
            {
                self.validatingAndSubmittingFinallyFunction();
            }
        }
    };

    return jQuery.proxy(submissionCallback, self);
}

, , . , .

+5
1

, JSON, ( JavaScript, ):

var data;
try{
  data = JSON.parse(jsonString);
}catch(e){
  // handle the error here, if you like
}
if (typeof data !== "undefined"){
  // Yay, we got some!
}

try...catch MDN.

( Chrome):

> try{ JSON.parse('3/') }catch(e){ console.log('oh no!') }; console.log('OK!')
"oh no!"
"OK!"
+4

All Articles