Reputation: 7325
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?
Upvotes: 1
Views: 939
Reputation: 149538
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
}
}
Upvotes: 1