如何捕捉exception?

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

这就是我调用我的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; } 

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

此时我必须抓住exception

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

如果有人给我提示如何在它停止程序之前捕获它。

有400个,401,402个错误,如果有什么问题,API会发送json

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

但那些点停止了json并停止了程序..

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

实际上,API会发送错误。 例如,状态将是; — 401 UNAUTHORIZED和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以下我应该写什么?

{“reason”:“电子邮件已注册。”,“成功”:false}

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

您正在寻找的是一个try-catch语句:

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

使用WebException作为catch语句中的类型意味着只catch该特定类型的exception。

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

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

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

您可以通过以下方式处理Webexception以获取HttpStatusCode和Response Message:

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

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

这对我有用。 我想我并没有阅读整个回复..所以我认为我认识的一些,现在它的工作……

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