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

标签 ajax angularjs asynchronous error-handling

背景

  • 我的 Angular 应用程序通过一组 API 端点与数据库进行通信。
  • “用户/身份验证”端点接受用户名和密码并返回成功 (200) 或错误请求 (400) http 响应。

  • Controller
    authService.login(email, password)
        .success(function (response) {
            /* go to application */
        })
        .error(function (response) {
            /* display proper error message */
        });
    

    认证服务
    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'}
        });
    }
    

    问题

    当用户名和密码失败并且 API 返回 400 响应时,即使我捕获了错误并向用户显示了正确的消息,错误也会出现在浏览器控制台中。
    POST http://myserver/user/authenticate 400 (Bad Request)
    

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

    最佳答案

    尝试这个

    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'}
        }).then(function (response) {
           /**Check here your status code 400 if you found that status code is 400 the reject the promise**/
                if (statuscode !==400) {
                            return response.data;
                        } else {
                            // invalid response
                            return $q.reject(response.data);
                        }
    
            }, function (response) {
                // something went wrong
                return $q.reject(response);
            });
    }
    

    然后使用以下代码
     authService.login(email, password)
            .then(function (response) {
                /* go to application */
            },function(error) {
                    console.log(error); /* catch 400  Error here */
        });
    

    关于ajax - 如何在 Angular 中捕获 http 错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31487785/

    相关文章:

    c# - Task.Run() 和 await Task.Run() 有什么区别?

    asp.net - 使用 CORS 的跨域图像文件上传问题 - ASP.NET Web API 和 jQuery

    javascript - 动态创建的 DIVS 中的 JQuery UI 选项卡

    javascript - 单张分隔的div元素交互

    javascript - 使用javascript聚焦后立即在Android上输入松散焦点

    javascript - 在 Controller 之前执行指令代码

    javascript - Ajax 调用后设置元素格式

    javascript - 用返回值初始化对象

    javascript - 在继续更改 DOM 函数之前如何等待异步数据库调用解析?

    multithreading - 比较 GCD 与 performSelectorInBackground : dispatch_async not in background