开发者

Exception Handling in REST

I have created a 开发者_开发问答REST service using WCF for communicating with BLL/DAL from UI. Now, I would like to implement Exception Handling through some globalize way in REST. I am using HTTPClient to communicate with REST from client. The following are the ways, I have implemented exception handling:

Approach 1:

OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = System.Net.HttpStatusCode.Unauthorized;
response.StatusDescription = ex.Message;
success = false;

Approach 2:

throw new WebProtocolException(HttpStatusCode.NotFound, ex.Message, null);

but somehow I am not able to catch them in the client side. Kindly suggest some pointers in order to handle exceptions raised by service globally.


I am throwing WebProtocolException (Approach 2) along with error code and error message from the service to UI in order to notify users about the exception. I am able to receive the error code in UI side but not getting error message or detail.

Then I created another service (having .svc extension) and added following line to the service's markup: "Factory='Microsoft.ServiceModel.Web.WebServiceHost2Factory'". Now, I am able to receive the error message along with error code on client side (UI).

Can anybody let me know how to use the WebServiceHost2Factory method in my existing service which is a class file instead of .svc file?

Any suggestions will be highly appreciated. Thanks


HttpClient does not throw exceptions when a response comes back that is not "successful". If you really want exceptions to be thrown on the client side, then call

response.EnsureResponseIsSuccessful();

Otherwise, just check the status code on the client and decide what to do based on that value.

You cannot throw exceptions on the server and expect the exceptions to be propagated to the client. HTTP does not have any notion of exception.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜