wcf 异常 抛出json格式的异常消息


// 自定义错误处理: 屏蔽发送给客户端错误信息,自己处理错误信息
public class ErrorHandler : IErrorHandler
{
string time = ""; //记录错误发生的时间,以便到日志文件中查询错误信息

//由于调用 ProvideFault 时,客户端处于阻塞状态,不要在这里进行长时间的操作
public void ProvideFault(Exception error, MessageVersion version, ref Message msg)
{
//避免敏感信息泄漏,例如:数据库配置, error包含的错误信息应该记录到服务器的日志中,不能显示给客户端
// FaultException<int> e = new FaultException<int>(123, error.Message);
DateTime now = DateTime.Now;
time = now.ToString("yyyyMMddHHmmssfff", DateTimeFormatInfo.InvariantInfo);// "" + now.Year.ToString() + now.Month.ToString() + now.Day.ToString() + now.Hour.ToString() + now.Minute.ToString() + now.Second.ToString() + now.Millisecond.ToString();
string errorMsg = "服务内部错误_" + time;
// FaultException fe = new FaultException(errorMsg);
// MessageFault mf = fe.CreateMessageFault();
// msg = Message.CreateMessage(version, mf, fe.Action);//返回的将是一个xml

//The fault to be returned
msg = Message.CreateMessage(version, "", errorMsg, new DataContractJsonSerializer(typeof(string)));

// tell WCF to use JSON encoding rather than default XML
WebBodyFormatMessageProperty wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

// Add the formatter to the fault
msg.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

//Modify response
HttpResponseMessageProperty rmp = new HttpResponseMessageProperty();

// return custom error code, 500.
rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
rmp.StatusDescription = "InternalServerError";

//Mark the jsonerror and json content
rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
rmp.Headers[HttpResponseHeader.ContentEncoding] = "utf-8";
rmp.Headers["jsonerror"] = "true";

//Add to msg
msg.Properties.Add(HttpResponseMessageProperty.Name, rmp);
}


//HandleError 在异常返回给客户端之后被触发
//自定义错误信息,例如在数据库中添加一个记录
public bool HandleError(Exception error)
{
string errorMsg = error.Message + " ===== " + error.StackTrace;
Logger logger = LogManager.GetCurrentClassLogger();
logger.Error(time + " ===== " + errorMsg);//文本日志
LgcComm.AddLog(errorMsg, time);//数据库日志
return false;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值