WCF JSON Service Error Handling


Sample code to demonstrate WebFaultException usage…

    [DataContract(Name = "error")]
    [Serializable]
    public class ErrorDetail
    {
        [DataMember(Name = "code")]
        public string ErrorCode;
        [DataMember(Name = "message")]
        public string Message;
    }

    [DataContract(Name = "errors")]
    [Serializable]
    public class ErrorDetails: List<ErrorDetail> {}


	[WebGet(UriTemplate = "/get.json?cd={code}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
	public InfoData GetInfo(string code)
	{
		if (string.IsNullOrWhiteSpace(code))
			throw new WebFaultException<ErrorDetail>(new ErrorDetail() { ErrorCode = "100", Message = "Parameter code is null" }, System.Net.HttpStatusCode.BadRequest);
			
		try
		{
			//Do something
		}
		catch (Exception ex)
		{
			Log.LogError(ex, "GetInfo...");
			throw new WebFaultException<ErrorDetail>(new ErrorDetail() { ErrorCode = "500", Message = "Unexpected error occurred..." }, System.Net.HttpStatusCode.InternalServerError);
		}
		finally
		{
		}
	}
Tagged with: ,
Posted in WCF
One comment on “WCF JSON Service Error Handling

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Antek Group Blog
Categories
%d bloggers like this: