我在我的应用程序服务器中遵循 MVC 模式。我正在尝试抛出异常,但未正确抛出。
这是来自 Controller 的代码:
[HttpPost]
public IHttpActionResult PostAddSuperUser(SuperUserViewModel SU)
{
try
{
//more code
blHandler.addSuperUser((SuperUser)SU.user, SU.Password);
return Ok();
}
catch (EUserAlreadyExist ex)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
resp.Content = new StringContent(string.Format("Already exist ", SU.user.Mail));
resp.ReasonPhrase = "Already exist";
throw new HttpResponseException(resp);
}
然后客户端调用如下:
try{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:50687/");
HttpResponseMessage response = await client.PostAsJsonAsync<SuperUserViewModel>("/api/SuperUser/PostAddSuperUser", SUVM);
if (response.IsSuccessStatusCode)
{
new SuccesPupUp("", "SuperUser " + SupUserName + " was added");
}
this.Close();
}
}
catch (HttpResponseException Exc)
{
new ErrorPopUp("", Exc.Message);
}
根据这个this我正确地抛出它,但是当我运行它时我得到了这个错误
我该如何解决?
编辑:我想向客户端抛出异常,以便它可以向用户询问新的电子邮件地址
最佳答案
问题出在这段代码中(看起来很明显,但请耐心等待):
catch (EUserAlreadyExist ex)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
resp.Content = new StringContent(string.Format("Already exist ", SU.user.Mail));
resp.ReasonPhrase = "Already exist";
throw new HttpResponseException(resp);
}
发生的事情是,您从上面的尝试中捕获了一个 EUserAlreadyExist 异常,然后抛出了一个没有随附的 try-catch
block 的新异常。所以这意味着仅仅因为你在 catch 中抛出异常,它不会自动神奇地捕获它,你必须在你的 catch 中有一个单独的 try-catch
更进一步,客户端调用此 try-catch
也不会捕获抛出的异常,因为它们(catch
语句)正在捕获不同的异常类型比抛出的异常类型要多。
要修复它,您需要捕获在这种情况下抛出的异常 HttpResponseException
异常。所以这意味着您的代码可能看起来像这样:
catch (EUserAlreadyExist ex)
{
try{
var resp = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
resp.Content = new StringContent(string.Format("Already exist ", SU.user.Mail));
resp.ReasonPhrase = "Already exist";
throw new HttpResponseException(resp);
}
catch(HttpResponseException ex2)
{
//do something here with the exception
}
}
关于c# - 如何使用 Web 服务正确抛出和处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30516426/