在客户端捕获异常消息

时间:2014-03-29 06:30:45

标签: c# asp.net-web-api

我在c#中学习web api。我想知道如何从服务器端发送的响应对象中捕获异常消息。

假设这是服务器端抛出的响应异常消息。所以我如何在客户端捕获它。通过使用正常的尝试捕捉它没有显示消息。

try
{
}
catch{Exception exception)
{

var errorMessage = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(exception.Message) };
                    throw new HttpResponseException(errorMessage);
}

2 个答案:

答案 0 :(得分:3)

这取决于谁是Web API的客户端。

  • C#client" exception"风格 - 你不会收到直接的异常抛出。您应该自己检查返回的HttpResponseMessage

    using (var client = new HttpClient() { BaseAddress = "http://someurl.com" } )
    using (var responseMessage = await client.GetAsync("resources/123")
    {
        try
        {
            // EnsureSuccessStatusCode will throw HttpRequestException exception if 
            // status code is not successfull
            responseMessage.EnsureSuccessStatusCode();
    
            // Here you should process your response if it is successfull.
            // Something like
            // var result = await responseMessage.Content.ReadAsAsync<MyClass>();
        }
        catch (HttpRequestException)
        {
            var errorContent = await responseMessage.Content.ReadAsStringAsync();
            // "errorContent" variable will contain your exception message.
        } 
    }
    
  • C#client&#34; if&#34;风格 - 你也可以在不引发异常的情况下获得相同的结果

    if (responseMessage.IsSuccessStatusCode)
    {
        // Here you should process your response if it is successfull.
        // Something like
        // var result = await responseMessage.Content.ReadAsAsync<MyClass>();
    }
    else
    {
        var errorContent = await responseMessage.Content.ReadAsStringAsync();
        // "errorContent" variable will contain your exception message.
    }
    
  • JavaScript - 取决于您将用于调用服务的库,但通常它们都提供了一些错误回调参数,您可以在其中传递错误处理函数。

答案 1 :(得分:0)

我只想添加从服务器端向客户端发送异常的整个过程:

1-在服务器端:

[HttpGet]
public HttpResponseMessage DoSomething([FromUri] string ValtoProcess)
{
    try
    {
       return ControllerContext.Request.CreateResponse(HttpStatusCode.OK, new { result, message });
    }
    catch(exception ex)
    {
       HttpResponseMessage Response =Request.CreateErrorResponse(HttpStatusCode.InternalServerError,ex.InnerException.Message);
            throw new HttpResponseException(Response);
     }

然后在客户端只是在响应状态不正常的情况下读取错误如下:

string ErrorMessage = await TaskReponse.Content.ReadAsStringAsync();