Как реагировать на SyntaxError в javascript

Я получаю данные с php-сервера, и иногда он выдает предупреждения. Эти предупреждения приводят к тому, что анализ ответа выдает синтаксическую ошибку, которая игнорирует весь имеющийся у меня код try/catch и просто останавливает обработку, оставляя сложные объекты в частичном состоянии, которое невозможно восстановить.

Как я могу отловить эти ошибки? Я хочу иметь шанс вернуть объект в какое-то устойчивое состояние.

В идеале я бы не получал ответов о том, что мне следует переосмыслить архитектуру или изменить настройки php. Я хотел бы знать, как реагировать на SyntaxErrors, выдаваемые JSON.parse().

Спасибо, Jeromeyers

РЕДАКТИРОВАТЬ:

До меня дошло, что проблема сложнее, чем я первоначально думал. Это код, который не перехватывает SyntaxError:

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
задан argyle 29 May 2012 в 21:10
поделиться