小编use*_*656的帖子

如何在Angular中捕获http错误响应

背景

  • 我的Angular应用程序通过一组API端点与数据库通信.
  • "user/authenticate"端点接受用户名和密码,并返回成功(200)或错误请求(400)http响应.

调节器

authService.login(email, password)
    .success(function (response) {
        /* go to application */
    })
    .error(function (response) {
        /* display proper error message */
    });
Run Code Online (Sandbox Code Playgroud)

身份验证服务

factory.login = function(email, password) {
    return $http({
        method: 'POST',
        url: "http://myserver/user/authenticate",
        data: $.param({email: email, password: password}),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
}
Run Code Online (Sandbox Code Playgroud)

问题

当用户名和密码失败并且API返回400响应时,即使我正在捕获错误并且我向用户显示正确的消息,该错误也会出现在浏览器控制台中.

POST http://myserver/user/authenticate 400 (Bad Request)
Run Code Online (Sandbox Code Playgroud)

我能以更好的方式处理错误吗?

ajax error-handling asynchronous angularjs

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

ajax ×1

angularjs ×1

asynchronous ×1

error-handling ×1