Reputation: 3199
I am using Breeze.js and Q.js within my MVC app.
I currently have an action on my webApi
public IQueryable<Myobject> doMyAction()
This can do 2 things:
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized, "Not Allowed"));
var query = EntityQuery.from('doMyAction');
// execute the query
dcCore.manager.executeQuery(query)
.then(querySucceeded)
.fail(dcCore.queryFailed);
If the user is authorised and the logic is true, then I connect to my DB and return a nice list of Myobject() and everything is fine.
However, if I do a throw exception to say they are unauthorised, then in the console I get my 401 (Unauthorised) and the message:
[Q] Unhandled rejection reasons (should be empty):
This happens before it hits the .fail() function.
I also tried putting a try/catch around the whole execute bit, hoping that I would catch an error, but had no luck.
I can see why this is happening in theory, as I am not returning something that executeQuery is expecting (In fact, im not returning at all, i'm throwing!), however,
how should I handle returning errors from the webApi with breeze, without doing something like extending the model?
The only thing I am yet to try is to make my web API return a type of dynamic, or generic object, but this doesn't feel like the best solution.
Upvotes: 0
Views: 213
Reputation: 17052
You have two approaches for this, the first is to simply throw an simple exception directly in your query method, i.e. something like this:
[HttpGet]
public IQueryable<Customer> CustomersStartingWith(string companyName) {
if (companyName == "null") {
throw new Exception("nulls should not be passed as 'null'");
}
...
}
Or, if you want slightly more control over the HTTPResponse you can do the following:
[HttpGet]
public IQueryable<Customer> CustomersWithHttpError() {
var responseMsg = new HttpResponseMessage(HttpStatusCode.NotFound);
responseMsg.Content = new StringContent("Custom error message");
responseMsg.ReasonPhrase = "Custom Reason";
throw new HttpResponseException(responseMsg);
}
Note that for a Save operation as opposed to the Query operations described above, the best approach is to throw an EntityErrorsException. (see documentation), although throwing a simple exception will still work.
Hope this helps.
Upvotes: 1