如何在javascript中响应SyntaxError

我从PHP服务器获取数据,有时它会抛出警告.这些警告导致解析响应抛出语法错误,该错误违反了我所有的try / catch代码并且只是停止处理,使复杂对象处于无法恢复的部分状态.

我怎样才能发现这些错误?我希望有机会让对象恢复稳定状态.

理想情况下,我不会收到答案,说我应该重新考虑架构或更改PHP设置.我想知道如何响应JSON.parse()抛出的SyntaxErrors.

谢谢,
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,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);
}

那里真的发生了很多事情,而且很多结构都适合它.我不知道包括它会不会真的有帮助.

最佳答案
假设您正在谈论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 at MDN.

例如(来自Chrome的控制台):

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...