如何创建角度承诺中捕获的错误

How to create an error that is captured in angular promise

本文关键字:承诺 错误 何创建 创建      更新时间:2023-09-26

我正在努力了解如何在angular中找到.then()的拒绝部分。

C#方法

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

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

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

引发HttpResponseException或返回Request.CreateErrorResponse?

示例角度法

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

如果我没有解释好,请告诉我,我只是在了解reject部分的功能。

您应该返回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);
    }
}

我想你的一个括号搞砸了。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?
});

希望能有所帮助。