Ответ 1
РЕДАКТИРОВАТЬ: Обновлено сообщение с надлежащим пользовательским обработчиком ошибок json
Быстрый, но не предваряемый способ.
<serviceDebug includeExceptionDetailInFaults="true"/>
В вашей службе поведение даст вам все необходимые сведения.
Приятный способ
Все исключения из приложения преобразуются в JsonError
и сериализуются с использованием DataContractJsonSerializer
. Exception.Message
используется напрямую. FaultExceptions предоставляют код FaultCode, а другое исключение обрабатывается как неизвестное с кодом ошибки -1.
FaultException отправляются с кодом состояния HTTP 400, а другие исключения - это код HTTP 500 - внутренняя ошибка сервера. Это не так важно, поскольку код ошибки может быть использован для определения, есть ли это и неизвестная ошибка. Это было удобно в моем приложении.
Обработчик ошибок
internal class CustomErrorHandler : IErrorHandler
{
public bool HandleError(Exception error)
{
//Tell the system that we handle all errors here.
return true;
}
public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
{
if (error is FaultException<int>)
{
FaultException<int> fe = (FaultException<int>)error;
//Detail for the returned value
int faultCode = fe.Detail;
string cause = fe.Message;
//The json serializable object
JsonError msErrObject = new JsonError { Message = cause, FaultCode = faultCode };
//The fault to be returned
fault = Message.CreateMessage(version, "", msErrObject, new DataContractJsonSerializer(msErrObject.GetType()));
// tell WCF to use JSON encoding rather than default XML
WebBodyFormatMessageProperty wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
// Add the formatter to the fault
fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
//Modify response
HttpResponseMessageProperty rmp = new HttpResponseMessageProperty();
// return custom error code, 400.
rmp.StatusCode = System.Net.HttpStatusCode.BadRequest;
rmp.StatusDescription = "Bad request";
//Mark the jsonerror and json content
rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
rmp.Headers["jsonerror"] = "true";
//Add to fault
fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
}
else
{
//Arbitraty error
JsonError msErrObject = new JsonError { Message = error.Message, FaultCode = -1};
// create a fault message containing our FaultContract object
fault = Message.CreateMessage(version, "", msErrObject, new DataContractJsonSerializer(msErrObject.GetType()));
// tell WCF to use JSON encoding rather than default XML
var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
//Modify response
var rmp = new HttpResponseMessageProperty();
rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
rmp.Headers["jsonerror"] = "true";
//Internal server error with exception mesasage as status.
rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
rmp.StatusDescription = error.Message;
fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
}
}
#endregion
}
Webbehaviour используется для установки вышеуказанного обработчика ошибок
internal class AddErrorHandlerBehavior : WebHttpBehavior
{
protected override void AddServerErrorHandlers(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
base.AddServerErrorHandlers(endpoint, endpointDispatcher);
//Remove all other error handlers
endpointDispatcher.ChannelDispatcher.ErrorHandlers.Clear();
//Add our own
endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(new CustomErrorHandler());
}
}
Контракт данных json error
Определяет формат ошибки json. Добавьте свойства здесь, чтобы изменить формат ошибки.
[DataContractFormat]
public class JsonError
{
[DataMember]
public string Message { get; set; }
[DataMember]
public int FaultCode { get; set; }
}
Использование обработчика ошибок
самопринятый
ServiceHost wsHost = new ServiceHost(new Webservice1(), new Uri("http://localhost/json"));
ServiceEndpoint wsEndpoint = wsHost.AddServiceEndpoint(typeof(IWebservice1), new WebHttpBinding(), string.Empty);
wsEndpoint.Behaviors.Add(new AddErrorHandlerBehavior());
App.config
<extensions>
<behaviorExtensions>
<add name="errorHandler"
type="WcfServiceLibrary1.ErrorHandlerElement, WcfServiceLibrary1" />
</behaviorExtensions>
</extensions>