【问题标题】:How to catch exception?如何捕捉异常?
【发布时间】:2015-06-06 12:49:10
【问题描述】:

我正在尝试调用 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 会停止程序,我希望它运行并接收响应。

实际上,API 会发送错误。 例如,状态将是 ;---401 UNAUTHORIZED 并且响应将是

{ "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我应该写什么?

{ "reason": "邮箱已经注册。", "success": false }

请我是 C# 新手,如果有不清楚的地方请修改或提问? 谢谢你

【问题讨论】:

  • 有一本关于 C# 编程语言的完整手册。在询问有关语言语法的基本问题之前,您应该先查看它。见C# Programming Guide。详细参考请见C# Reference

标签: c# .net exception exception-handling


【解决方案1】:

您要查找的内容称为try-catch 声明:

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

catch 语句中使用WebException 作为类型意味着只会捕获该特定类型的异常。

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

【讨论】:

  • 但这会阻止我的回应吗???实际上,API 会发送错误。例如,状态将是 ;---401 UNAUTHORIZED 并且响应将是 { "reason": "Email already registered.", "success": false }
  • 如果GetResponse抛出一个被捕获的异常,代码执行流程将在catch块之后正常继续,除非该异常被重新抛出。
【解决方案2】:

您可以通过这种方式处理您的网络异常以获取 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;
    }
}

【讨论】:

  • 所以我应该在 catch 中称我为响应部分。因为如果出现错误,它不会得到任何响应。但我认为这会起作用..让我试试。给我15分钟..谢谢
  • catch (Exception e) { throw; } 只会浪费时间不必要地展开堆栈。
  • 谢谢,普雷斯顿。更新了帖子。
  • @YuriyAkopov 我已经更新了我的帖子,你能帮我解决这个问题吗.. 我没有得到回应 boby... 那么如何让你告诉我.. 请
  • @user3788832 您添加的代码不完整,无法处理 Web 异常。请在此处查看我对 facebook api 的示例请求dl.dropboxusercontent.com/u/46564414/StackOverFlow/… 它返回 HTTP400 以及 json 中的错误消息
【解决方案3】:

您封装任何您希望防止引发未处理异常的方法调用或代码块。

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

【讨论】:

  • 如果您不打算在处理中使用异常对象并且您计划捕获任何和所有异常(通常您不应该计划这样做),不需要在catch 表达式中声明类型。
  • 当然,这更像是一种澄清。为了表明您可以指定在需要时捕获特定异常。但是,是的,这是不必要的。
  • @noMad17:-- 但这会阻止我的回应吗???实际上,API 会发送错误。例如,状态将是 ;---401 UNAUTHORIZED 并且响应将是 { "reason": "Email already registered.", "success": false } –
  • 如果您的应用程序抛出异常,您将最终进入 catch-block 内部,并且从那里您可以什么都不做(不建议这样做,因为某些事情显然是错误的)或者您可以修复一些替代解决方案的问题,代码将继续,就好像什么都没发生一样。
  • @noMad17 正如我在问题中提到的,它将返回状态 401、402 或 400 .. 它会停止.. 让我尝试 try-catch,如果我成功获得响应,那么我认为有问题解决了。​​
【解决方案4】:

好的,我终于可以解决这个问题了。谢谢大家的帮助。

这对我有用。我想我没有阅读完整的回复..所以我认为我是如何意识到的,现在它正在工作..

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);
            }

【讨论】:

    猜你喜欢
    • 2012-03-20
    • 1970-01-01
    • 2012-01-10
    • 2013-03-29
    • 2021-10-17
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多