how to handle HTTP errors in emberJs while using ember-data with RESTAdapters? - rest

I have a route /products. In App.ProductsRoute, I am using a setupController hook to assign list of products fetched from server to local App.Product objects.
I am setting the model in setupController hook as :
self_controller.set('model', self_controller.store.find('product'));
This works well when HTTP status is 200. But when server returns some HTTP error (like 500-Internal Server Error, 401-Unauthorized Errors, etc) I am getting error as JSON.parse. I am not sure how to handle errors for this.store.find() calls.
Note: It returns Ember's promiseArray which I need to check once resolved (before actually assigning it to model). Any help on this topic would be much appreciated. Thanks.

What about using the promise's catch callback to handle the errors? Untested, but something like this should work:
self_controller.store.find('product').then(function(products) {
self_controller.set('model', products);
}).catch(function(reason) {
// Do something to handle the error response...
});

Related

I need simple proxy between 2 rest APIs

My code is working ok for GET/POST/PUT to/from restApi1 and restApi2.
However, my problem I need to implement HEAD/OPTIONS (no body!) and GET uri1
HEAD/OPTIONS could return 204 or 200 depends on a process status. I am getting error "Stream closed". Sounds like Camel want body bytes, but I don't indend to have it. Even I set ExchangePattern.InOnly or optional etc error occur...
What is correct way to see responses and handle requests WITHOUT body, just statuses exchange?
How to see response from restApi2 on Camel rest("/restApi1").head().route().routeId("id1")
.to("direct:restApi2").routeId("/id1").setHeader(Exchange.HTTP_METHOD,constant("HEAD"))
setExchanggePattern(ExchangePattern.OutOptionalIn).recepientList(simple(restApi2));
I figured it out. Need to set '.convertBodyTo(String.class)' even I don't have a body.

Route SockJS connection at variable URL?

Let's say I have a bunch of clients who all have their own numeric IDs. Each of them connect to my server through SockJS, with something like:
var sock = new SockJS("localhost:8080/sock/100");
In this case, 100 is that client's numeric ID, but it could be any number with any number of digits. How can I set up a SockJS router in my server-side code that allows for the client to set up a SockJS connection through a URL that varies based on what the user's ID is? Here's a simplified version of what I have on the server-side right now:
public void start() {
HttpServer server = vertx.createHttpServer();
SockJSHandler sockHandler = SockJSHandler.create(vertx);
router.route("/sock/*").handler(sockHandler);
server.requestHandler(router::accept).listen(8080);
}
This works fine if the client connects through localhost:8080/sock, but it doesn't seem to work if I add "/100" to the end of the URL. Instead of getting the default "Welcome to SockJS!" message, I just get "Not Found." I tried setting a path regex and I got an error saying that sub-routers can't use pattern URLs. So is there some way to allow for the client to connect through a variable URL, whether it's /sock/100, /sock/15, or /sock/1123123?
Ideally, I'd be able to capture the numeric ID that the client uses (like with routing REST API calls, when you could add "/:ID" to the routing path and then capture the value that the client uses), but I can't find anything that works for SockJS connections.
Since it seems that SockJS connections are considered to be the same as sub-routers, and sub-routers can't have pattern URLs, is there some work-around for this? Or is it not possible?
Edit
Just to add to what I said above, I've tried a couple different things which haven't seemed to work yet.
I tried setting up an initial, generic main router, which then re-directs to the SockJS handler. Here's the idea I had:
router.routeWithRegex("/sock/\\d+").handler(context -> {
context.reroute("/final");
});
router.route("/final").handler(SockJSHandler.create(vertx));
With this, if I access localhost:8080/sock/100 directly through the browser, it takes me to the "Welcome to SockJS!" page, and the Chrome network tab shows that a websocket connection has been created when I test it through my client.
However, I still get an error because the websocket shows a 200 status code rather than 101, and I'm not 100% sure as to why that is happening, but I would guess that it has to do with the response that the initial handler produces. If I try to set the initial handler's status code to 101, I still get an error, because then the initial handler fails.
If there's some way to work around these status codes (it seems like the websocket is expecting 101 but the initial handler is expecting 200, and I think I can only pick one), then that could potentially solve this. Any ideas?

Calling error component from sightly java

I have a sightly java class(a java class included inside component) which calls an api and checks whether the response in null. If its null, I have to call the error component. When I am setting the response status as 404, it is not working because before executing that line, it is taking the response as 200. How to call the error component in this case.
Note: I have tried redirecting the URL to error.html, but thats not the proper solution.
It is generally bad practice to redirect or change the response status from a component/view as the response might already have some content that was committed.
You might want to redesign you application to either:
Call the remote API at the beginning of the request handling and, if the remote API returns null, return a 404 before anything else is committed to the response.
Handle the null response from the remote API by either:
Rendering an appropriate response, in case the null response is expected/permitted in some cases.
Throwing an exception, which will result in status 500, in case the null response is not expected.

Camel does not set 'Transfer-Encoding chunked' in case response is prepared by exception handler processor

I am implementing REST services using Apache-CXF running on servicemix and for that I have a camel route that does some processing, sends the message over queue, process some more and send back the reply. Something like this:
from("direct:start")
.process(A)
.process("activemq:abc")
.process(B);
On this route I have applied some basic validation and exception handler and when I have to stop the route in both cases, I use something like this:
exchange.getOut().setBody(response);
exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
I use soap UI, restclient-UI and putty to make http requests and I get proper response body displayed in all of them. Now I wanted to preserve request headers so I made a little change everywhere in the code so that response bodies are set in exchange.getIn() only. For example: in case of validation failure I do:
exchange.getIn().setBody(response);
exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
Just with this little change, the rest clients I am using to make request stopped displaying the response body. As per the server logs, response is being generated and also as per the logs in rest client, I am getting the proper response but they are unable to display the response body only in case when I stop the route in between. Normal response is displaying just fine. Only the restclient-UI was considerate enough to show the error as to why they are not displaying body and the error is:
Byte array conversion from response body stream failed.
Diggin deeper, I found the only response header which was there in success response but missing in error response:
Transfer-Encoding chunked
Error response is around 1000 characters long and contains a header called content-length. I am not sure but I think the problem has something to do with this itself. I would really like to play with exchange.getIn but these different kind of responses prepared by camel are confusing me. How can I make sure my camel responses are always displayed properly?
The Content-Length header will be preserved from the original request so you need to remove it so that camel cxf can work out the new body length on the response and set Content-Length with that.

Exception Handling in REST

I have created a REST service using WCF for communicating with BLL/DAL from UI. Now, I would like to implement Exception Handling through some globalize way in REST. I am using HTTPClient to communicate with REST from client. The following are the ways, I have implemented exception handling:
Approach 1:
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = System.Net.HttpStatusCode.Unauthorized;
response.StatusDescription = ex.Message;
success = false;
Approach 2:
throw new WebProtocolException(HttpStatusCode.NotFound, ex.Message, null);
but somehow I am not able to catch them in the client side. Kindly suggest some pointers in order to handle exceptions raised by service globally.
I am throwing WebProtocolException (Approach 2) along with error code and error message from the service to UI in order to notify users about the exception. I am able to receive the error code in UI side but not getting error message or detail.
Then I created another service (having .svc extension) and added following line to the service's markup: "Factory='Microsoft.ServiceModel.Web.WebServiceHost2Factory'". Now, I am able to receive the error message along with error code on client side (UI).
Can anybody let me know how to use the WebServiceHost2Factory method in my existing service which is a class file instead of .svc file?
Any suggestions will be highly appreciated. Thanks
HttpClient does not throw exceptions when a response comes back that is not "successful". If you really want exceptions to be thrown on the client side, then call
response.EnsureResponseIsSuccessful();
Otherwise, just check the status code on the client and decide what to do based on that value.
You cannot throw exceptions on the server and expect the exceptions to be propagated to the client. HTTP does not have any notion of exception.