Hi,
I try to used a JSON API back-end secured by keycloak. This back-end reponse with a 401 www-autenticate.
The problem is that i’m unable to retrieve the status code of the error. I’ve tried to overwrite the adapter.handleResponse(). But this does not work.
The application route error object does not contains the status code. Any idea how to handle this case?
Hi @scandinave! I’ve used the error hook in the route to handle such things. See the docs for more information, but what I’ve done for this & other types of errors:
I am also trying to react to 401 status codes. I can not find any working example. Is there another way I can globally catch 401 or any bad status code errors in octane? What I did is adding the following to
app/routes/application.js:
@Dantelthe guides show an example of what you’re trying to do I think. However it looks like you should use the action decorator, and the example is also using replaceWith instead of transitionTo:
IIRC this will only intercept errors encountered while transitioning (and only on the route you’re using this action on). So if you want to intercept errors more “globally” you may want to consider handling this at a different level in addition/instead. For example in Ember Simple Auth errors this logic is handled in the handleResponse method of the application adapter so (assuming you use Ember Data) any request made via Ember Data that receives a 401 response will redirect to login route.
EDIT: replaceWith is probably what you want to use but it really only affects history entries IIRC so probably not a big deal either way
thanks a lot, this is really helpful! I actually did already try to override “handleResponse” in the application adapter, just like shull demonstrated above. But I can actually do something like this:
handleResponse(status, headers, _payload, requestData) {
if(status === 401) {
//do NOT return any error, instead handle it here
}
return super.handleResponse(status,headers,_payload,requestData);
}
Putting an alert in there triggered it every time, so this is nice. But now I am in the adapter and not in the route anymore. Is there any simple and clean way to call replaceWith/transitionTo outside of a route? So I could hook in my error handling in handleResponse and then transition from there.
You can inject the router service pretty much anywhere you need to, and use that to transition. So you could inject the router service into your application adapter and then use it in the handleResponse method, something like:
import { inject as service } from '@ember/service';
...
@service router;
...
handleResponse(status, headers, _payload, requestData) {
if(status === 401) {
this.router.transitionTo('login');
}
return super.handleResponse(status,headers,_payload,requestData);
}
...
Ah nice, a router service. So I guess I’ll create an error_handling service which will handle the dirty work and hook it into handleResponse to keep the adapter clutter free.