1 public class ECOrderException : Exception 2 {
//第一种类型: throw new ECOrderException { ErrorCode = "X1008-06", TransMessage = "SNs格式错误" }; 3 public ECOrderException() : base() 4 { 6 } 8 public virtual string ErrorCode { get; set; } 9 public virtual string TransMessage { get; set; } 10 //第二种类型:throw new ECOrderException("CO,WHSE 等栏位不能为空"); 11 //public ECOrderException(string Message): base(Message) 13 //{ 14 // TransMessage = Message; 15 //} 16 }
public class VWSException : Exception { public VWSException() : base() { } public string ErrorCode { get; set; } public string TransMessage { set; get; } public VWSException(string Message) : base(Message) { TransMessage = Message; } }
throw new VWSException { ErrorCode = "03", TransMessage = $"SO Confirm Failed,{ex.Message}" };
上面,有两个虚拟字段Error_Code和TransMessage
使用的时候,可以这样使用:
throw new ECOrderException { ErrorCode = "X1008-01", TransMessage = "交易代码验证失败" };
var obj = new JObject( new JProperty("head", new JObject(
new JProperty("transMessage", transMessage), new JProperty("errorCode", ErrorCode) )), new JProperty("body", new JObject()) ); var result = new ContentResult() { Content = Newtonsoft.Json.JsonConvert.SerializeObject(obj), ContentType = "application/json" };
然后这样就可以返回一个Json的格式信息给前端。
⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
ASP.NET Web API 异常处理 HttpResponseException 以及Angularjs获取异常信息并提示
一、HttpResponseException
如果一个Web API控制器抛出一个未捕捉异常,默认地,大多数异常都会被转化成一个带有状态码“500 – 内部服务器错误”的HTTP响应。HttpResponseException(HTTP响应异常)类型会返回你在异常构造器中指定的任何HTTP状态码。例如,在以下方法中,如果id参数非法,会返回“404 — 未找到”。
public Product GetProduct(int id) { Product item = repository.Get(id); if (item == null) { //指定响应状态码 throw new HttpResponseException(HttpStatusCode.NotFound); } return item; }
为了对响应进行更多控制,你也可以构造整个响应消息HttpResponseMessage,并用HttpResponseException来包含它:
public Product GetProduct(int id) { Product item = repository.Get(id); if (item == null) { var resp = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(string.Format("No product with ID = {0}", id)), ReasonPhrase = "Product ID Not Found" } //包含一个HttpResponseMessage throw new HttpResponseException(resp); } return item; }
if (order == null) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); }