Ajax: Passing exceptions from WCF service to javascript client
In my first experience with Ajax against WCF Http facade, I needed to pass exceptions from my WCF service back to the browser client. Researching WCF yielded clear understanding that the way of passing exceptions from WCF services to clients is SOAP faults. Numerous examples elaborate using FaultContracts and FaultExceptions. There is only one problem: SOAP faults are not supported in browsers hence have no use in Ajax.
Luckily, there is a very simple way of sending errors to browsers. If you are interested in communicating all exception details, look at this thread: WCF Services with faultexception. I wanted to pass just a single string with error text so I made a much shorter version of the solution offered in the thread:
public class MyService
{ [OperationContract]
public ResponseData<String> MyMethod()
{ ResponseData<String> result = new ResponseData<String>();
try
{ result.Result = GetMyResult();
}
catch (Exception ex)
{ result.ErrorMessage = ex.Message;
}
return result;
}
}
[DataContract]
public class ResponseData<T>
{ private string errorMessage;
[DataMember]
public string ErrorMessage
{ get { return this.errorMessage; } set
{ this.errorMessage = value;
this.IsError = value != null;
}
}
[DataMember]
public bool IsError { get; set; }
[DataMember]
public T Result { get; set; } }
Here is the client-side code:
<script type="text/javascript">
function getMyResult() { MyService.MyMethod(OnSucceeded);
}
function OnSucceeded(result) { if (!result.IsError) { // success
alert(result.Result);
}
else { // error;
alert(result.ErrorMessage);
}
}
</script>