Chaudhry Mohsin Ali Chaudhry Mohsin Ali - 3 months ago 15
C# Question

Web Api Exception Handling

In my app I am trying to use Exception handling. What I am trying to do is to create a separate class and extend it from HttpResponseException.

This is the code I have written until now,

public class ApiExceptions : HttpResponseException
{
public ApiExceptions(string reason, HttpStatusCode code)
{
var response = new HttpResponseMessage
{
StatusCode = code,
ReasonPhrase = reason,
Content = new StringContent(reason)
};
throw new HttpResponseException(response);
}
}


But I am getting this error,

'System.Web.Http.HttpResponseException' does not contain a constructor that takes 0 arguments


I am really new at exception handling in c#. I would really appreciate the help in this regard.

Answer

the following code should works

: base(...)

If you omit the call to a base constructor it will call the default base constructor automatically and HttpResponseException doesn't have without arguments.

 public class ApiExceptions : HttpResponseException
        {
            public ApiExceptions(string reason, HttpStatusCode code):base(code)
            {
                var response = new HttpResponseMessage
                {
                    StatusCode = code,
                    ReasonPhrase = reason,
                    Content = new StringContent(reason)
                };
                throw new HttpResponseException(response);
            }
        }

anyway i'm not sure why you need to extend HttpResponseException