【问题标题】:How to catch if ajax got wrong response type with jQuery如果 ajax 使用 jQuery 得到错误的响应类型,如何捕捉
【发布时间】:2013-12-16 11:35:13
【问题描述】:

我的 ajax 调用如下所示:

$.ajax({
     url: self.options.base_url + '/interface/jsonp/auth_user/',
     dataType: 'jsonp',
     success: function (data) {
         self._after_user_auth(data);
     },
     error: function () {
         self._service_unavailable()
     }
 });

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>

<head>
    <title>Unhandled Exception</title>
</head>

<body>
    <h1>Unhandled Exception</h1>
    <p>An unhandled exception was thrown by the application.</p>
</body>

</html>

如果服务器端出现错误,我会收到下一个响应

上升Uncaught SyntaxError: Unexpected token &lt;

有可能在客户端捕捉到吗?

【问题讨论】:

  • 发帖_service_unavailable()?有什么问题
  • @captain 好的,我明白了,_service_unavailable 已被触发(它只是在日志中写入有关它的信息,对异常本身不执行任何操作)但我的 chrome 控制台中仍然出现错误。

标签: javascript jquery ajax try-catch


【解决方案1】:

我不确定我是否理解你,但你可以用

捕捉 JavaScript 错误

try{}catch(){}:

$.ajax({
     url: self.options.base_url + '/interface/jsonp/auth_user/',
     dataType: 'jsonp',
     success: function (data) {
         try{
             self._after_user_auth(data);
         }catch(err){
             console.log(err); //catch is fired if inside try js find an error.
         }
     },
     error: function () {
         self._service_unavailable()
     }
});

catch(err) - err 是一个包含所有错误信息的对象。

一些文档:Try catch

【讨论】:

  • 不,它不起作用,就像您将整个 ajax 调用放在 try-catch 语句中一样,但感谢您的回答
猜你喜欢
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
  • 2011-04-14
  • 2019-06-23
  • 1970-01-01
  • 2013-02-12
  • 1970-01-01
  • 2019-12-01
相关资源
最近更新 更多