1

I am building a REST API using .net WEB API.

Here is a sample code

public class ValuesController : ApiController
    {

        // GET api/values
        public Values Get(int ID, int userID)
        {
            return new Values(){};
        }
}

Now what I want to do is return a different class if userID is not in allowed userID list. I was thinking of throwing an exception, but after I considered it I don't think that would be a good idea. Reason for this is that process was handled with OK status.

Basically I would like to return a custom ErrorMessage object instead of Values object. Is it possible to do it?

7
  • 1
    Throwing an exception is still valid. How about throw new HttpResponseException(HttpStatusCode.NotFound);? This is equivalent to a 404 response. Commented May 23, 2014 at 11:48
  • Why not change the status code to 400? What does Reason for this is that process was handled with OK status. mean Commented May 23, 2014 at 11:50
  • @DavidG I want to create and return a custom class containing additional "error" information. Commented May 23, 2014 at 11:50
  • @John With additional information throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound){ReasonPhrase = "Couldn't locate userID"}); Commented May 23, 2014 at 11:53
  • @YuvalItzchakov depending on how you view the problem. I could go with status 400, but how custom can I make the Response Exception? Commented May 23, 2014 at 11:54

1 Answer 1

1

IMO throwing an exception is valid when the flow of your code encounters an abnormal situation.

If you still dont want to throw, you can create a wrapper class that describes your result:

public class ValueResponse
{
   public HttpStatusCode HttpStatus { get; set; }
   public string ErrorMessage { get; set; }
   public Values Values { get; set; }
}

and return that object

public class ValuesController : ApiController
{

    // GET api/values
    public ValueResponse Get(int ID, int userID)
    {
        // Send a valid response or an invalid with the proper status code
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Good thinking. I have overseen it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.