如何捕捉异常

本文关键字:异常 何捕捉 | 更新日期: 2023-09-27 17:53:52

我试图调用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

例如,在创建用户时:——Email id已经存在

但是这个点会停止json和程序..

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

实际上,API会发送错误。例如,status为;——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": "Email已注册","success": false}

我是c#的新手,如果有什么不清楚的,请修改或提问?谢谢你

如何捕捉异常

您正在寻找的是所谓的try-catch语句:

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

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

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

你可以这样处理你的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;
    }
}

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

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

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

这对我有用。我想我没有阅读完整的回复。所以我想我是怎么意识到的,现在它起作用了。

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