如何在javascript中响应SyntaxError

arg*_*yle 5 javascript parsing json syntax-error

我从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,
                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);
}
Run Code Online (Sandbox Code Playgroud)

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

Phr*_*ogz 4

假设您正在谈论 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!
}
Run Code Online (Sandbox Code Playgroud)

try...catch在 MDN 上了解更多信息。

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

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

  • 它确实有效。打开控制台并输入:`try{ data = JSON.parse('{"foo":"bar"}'); }catch(e){ console.log("它不起作用") } if (typeof data != "undefined"){ console.log("它起作用了!") }`. 然后尝试使用错误的 JSON。 (2认同)