【问题标题】:How to create an error that is captured in angular promise如何创建在 Angular Promise 中捕获的错误
【发布时间】:2016-04-18 13:32:38
【问题描述】:

我试图了解如何以角度到达 .then() 的拒绝部分。

C#方法

public int Foo(){
 int foo = 1;
 return foo;
}

我已经尝试将HttpResponseException404500 一起抛出,但是即使该响应在.then() 承诺的第一部分中也被捕获和处理。我只是想了解需要发生什么样的错误才能进入后半部分。

我用这个作为源来抛出响应异常

Throw HttpResponseException or return Request.CreateErrorResponse?

角度方法示例

foo.then(function(response){
  //success do something
}), function(error){
   // how to come here?
})

如果我没有解释清楚,请告诉我,我只是在到达函数的reject 部分之后。

【问题讨论】:

  • 嘿 Harry,404 或 500 响应被视为成功呼叫。因为你问了,你收到了信息。当 http 调用不成功时会触发错误阶段。即超时。您可以通过在调用上设置一个非常短的超时来测试这一点,或者只是调用错误的路径或服务器。
  • 你有HTTP响应拦截器吗?
  • @stevenca 哦,我明白了,谢谢
  • 我会研究如何处理 Promise 中的异常。查看stackoverflow.com/q/36345046/215552stackoverflow.com/q/26534303/215552
  • 确定你有正确的答案 b4 你的人发布了这个例子 stackoverflow.com/questions/37286629/… 认为你应该得到支持!

标签: javascript c# angularjs


【解决方案1】:

您应该返回 IHttpActionResult,而不是从 C# 方法返回 int

[HttpGet]
public IHttpActionResult Foo()
{
    try 
    {
        int foo = 1;
        return Ok(foo);
    }
    catch(Exception exception)
    {
        // log exception or whatever you need to do
        return InternalServerError(exception);
    }
}

【讨论】:

  • 嗨,谢谢,但这不会被 .then() 的成功部分捕获
  • Ok() 响应会触发你的成功回调,而InternalServerError() 响应会触发错误回调。
【解决方案2】:

我认为你搞砸了你的括号之一。 Promise 的错误处理程序必须包含在“.then”方法中。

替换这个:

foo.then(function(response){
  //success do something
}), function(error){
   // how to come here?
})

foo.then(function(response){
  //success do something
}, function(error){
   // how to come here?
});

希望对您有所帮助。

【讨论】:

  • 嗨,谢谢,但代码是用于演示目的,这不能回答我的问题。
猜你喜欢
  • 1970-01-01
  • 2015-07-21
  • 2019-01-04
  • 2019-02-08
  • 1970-01-01
  • 2019-04-07
  • 2021-04-21
  • 2017-05-06
  • 2018-01-14
相关资源
最近更新 更多