如何捕捉异常?

时间:2015-06-05 20:17:00

标签: c# .net exception exception-handling

我正在尝试调用api并检查其响应,但是当传递了一些错误的值时它会停止程序。我想在请求和响应期间添加异常但不确定如何写入函数。

这就是我打电话给我的REST电话

public dynamic APICalls(JObject ljson, string endpoints, string method)
        {
            var httpReq = (HttpWebRequest)HttprequestObject(endpoints, method);
            using (var streamWriter = new StreamWriter(httpReq.GetRequestStream()))
            {
                streamWriter.Write(ljson);
                streamWriter.Flush();
                streamWriter.Close();
            }
            var httpResponse = (HttpWebResponse)httpReq.GetResponse();
            var result = "";
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }
            return result;
            //return "Success";
            //not sure what to return 
            //here i have to add sql server code to enter into database
        }

这是请求代码

public dynamic HttprequestObject(string endpoints, string method)
        {
            string url = Settings.API_TEST_VALUE + endpoints;
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = method;
            return httpWebRequest;
        }

在请求之前和响应后我想要捕获异常。

此时我必须抓住异常

 var httpResponse = (HttpWebResponse)httpReq.GetResponse();

如果有人给我提示如何在停止计划之前抓住它。

有400个,401,402个错误,如果出现错误,API会发送json

例如,在创建用户时: - 电子邮件ID已存在

但是那些点会停止json并停止程序..

使用try catch它将停止程序,我希望它运行并希望接收resposne。

实际上,API会发送错误。 例如,状态将是; --- 401未经授权 和resposnse将是

{ "reason": "Email already registered.", "success": false } 

我改变了我的代码和

   HttpWebResponse httpResponse; 
            try
            {
               //HttpWebResponse myHttpWebResponse = (HttpWebResponse)httpReq.GetResponse();
               httpResponse = (HttpWebResponse)httpReq.GetResponse();
               //myHttpWebResponse.Close();

               using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
               {
                   result = streamReader.ReadToEnd();
               }
            }
            catch (WebException e)
            {
                Console.WriteLine("This program is expected to throw WebException on successful run." +
                                    "\n\nException Message :" + e.Message);
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                    Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return result;
            //return "Success";
            //not sure what to return 
            //here i have to add sql server code to enter into database
        }

这是新代码,但我没有将Json作为返回值,所以我可以显示特定的错误。 对于Json以下我应该写什么?

{"原因":"电子邮件已经注册。","成功":false}

请问我是c#的新手,如果不清楚请修改或提出问题? 谢谢

4 个答案:

答案 0 :(得分:3)

您正在寻找的内容称为try-catch声明:

try
{
     var httpResponse = (HttpWebResponse)httpReq.GetResponse();
}
catch (WebException e)
{
    // Here is where you handle the exception.
}

使用WebException作为catch语句中的类型意味着只会抓住该特定类型的例外。

如果发生异常,e变量将包含异常详细信息,例如从方法传递的消息,其中包含三个异常以及封装在其中的任何内部异常。

答案 1 :(得分:2)

您可以通过以下方式处理Web异常以获取HttpStatusCode和响应消息:

public void SendAndGetResponseString()
{
    try
    {
        // Here you call your API
    }
    catch (WebException e)
    {
        var result = GetResponceFromWebException(e);
        if (result != null){
            // 
            // Here you could use the HttpStatusCode and HttpResponseMessage
            //
        }                   

        throw;
    }
    catch (Exception e)
    {
        // log exception or do nothing or throw it          
    }
}


private HttpRequestResponce GetResponceFromWebException(WebException e)
{
    HttpRequestResponce result = null;
    if (e.Status == WebExceptionStatus.ProtocolError)
    {
        try
        {
            using (var stream = e.Response.GetResponseStream())
            {
                if (stream != null)
                {
                    using (var reader = new StreamReader(stream))
                    {
                        var responseString = reader.ReadToEnd();
                        var responce = ((HttpWebResponse) e.Response);

                        result = new HttpRequestResponce(responseString, responce.StatusCode);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // log exception or do nothing or throw it
        }
    }
    return result;
}


public class HttpRequestResponce {
    public HttpStatusCode HttpStatusCode { get;set; }
    public string HttpResponseMessage {get;set;}

    public HttpRequestResponce() { }

    public HttpRequestResponce(string message, HttpStatusCode code)
    {
          HttpStatusCode=code;
          HttpResponseMessage=message;
    }
}

答案 2 :(得分:1)

您封装了要防止抛出未处理异常的任何方法调用或代码块。

try
{
    // code here
}
catch (Exception)
{
    // here you may do whatever you want to do when an exception is caught
}

答案 3 :(得分:0)

好的,最后我能解决这个问题。谢谢大家的帮助。

这对我有用。我想我并没有阅读完整的回复..所以我认为我认识到现在它的工作方式......

HttpWebResponse httpResponse;
            try
            {
                httpResponse = (HttpWebResponse)httpReq.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }
            }
            catch (WebException e)
            {
                Console.WriteLine("This program is expected to throw WebException on successful run." +
                                    "\n\nException Message :" + e.Message);
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                    Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                    using (Stream data = e.Response.GetResponseStream())
                    using (var reader = new StreamReader(data))
                    {
                        string text = reader.ReadToEnd();
                        Console.WriteLine(text);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }