0

I have a REST service and I want to have a helper class that handle exceptions

My code looks as follows:

[WebGet(UriTemplate = "/Test/{param}")]
public Stream Test(string param)
{
        if (param == "Ok")
            return Process(param);
        else
        {
            RESTException(System.Net.HttpStatusCode.BadRequest, "Param not ok");
            return null;
        }
}


private void RESTException(System.Net.HttpStatusCode httpStatusCode, string message)
{
        OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
        response.StatusCode = httpStatusCode; // or anything you want
        response.StatusDescription = message;
}

I test from browser, but when I pass wrong param, e.g.

http://myaddress/Service/Test/badparam

nothing shows up in the browser.

What is wrong in my code?

bzamfir
  • 4,698
  • 10
  • 54
  • 89

2 Answers2

1

Change

RESTException(System.Net.HttpStatusCode.BadRequest, "Param not ok");
return null;

to

RESTException(System.Net.HttpStatusCode.BadRequest, "Param not ok");
return "Param not ok";
Stig Hausberg
  • 836
  • 6
  • 9
  • Sorry, the web method should return Stream, not string. I don't want to explicitely return thr error message, but instead the browser to report the exception (e.g 400: BAD Request). Any suggestion? – bzamfir Feb 04 '12 at 15:06
  • Are you sure you are returning a 400 error? With firebug for Firefox or something similar you can inspect the http headers sent back from the server and make sure they contain a 400 bad request. – Stig Hausberg Feb 04 '12 at 15:37
0

I changed the RESTException as below, which throw the proper exception and slsdo show proper exception info when REST is tested from browser or from REST test client provided by REST WCF WebApi

    private void RESTException(SelectFault fault, System.Net.HttpStatusCode httpStatusCode)
    {
        throw new WebFaultException<string>(fault.ErrorMessage, httpStatusCode);
    }
bzamfir
  • 4,698
  • 10
  • 54
  • 89