Exception handling in REST service

1.6k views Asked by At

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?

2

There are 2 answers

0
bzamfir On BEST ANSWER

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);
    }
2
Stig Hausberg On

Change

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

to

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