Angular2 http error response status - error-handling

I'm trying to handle specific response codes in my Angular2 app. I have this code:
handleError(res: Response) {
console.log('Response status is %d', res.status);
if (res.status === 403) {
logUserOut();
}
}
The log statement there prints out Response status is 403, but the if statement is not true. Looking at the actual response object, it does look like the status is 403 and is an int. My first guess would have been the if statement is evaluating to false due to a different type. its a int not a string? I haven't tried using == instead of === because my linter would complain and not transpile. In any case, I'm trying to figure out why this seemingly true statement is evaluating to false.

Related

Axios triggering weird in React native app

Hello i have a weird thing going on,im using axios in order to send post-get http request for my app.The thing is that axios in my pc working good but in my laptop need console.log("") before axios request i dont know why.This happens in all my files.
It gives me this error : Possible Unhandled Promise Rejection (id : 0 ):
[Axios error: Request failed with statis code 404]
Here is my code :
function getProfile(){
try{
//console.log("") <-------------------------- Here i put it
axios.post(URL+'/checkData',
{
usernameCheckAXIOS : username,
passwordCheckAXIOS : password,
})
.then((response)=>{
console.log(response.data)
setProfile(response.data);
if(response.data.responseOfProfile == false){
Alert.alert("Access Dinied")
}
else{
navigation.navigate('Home')
}
})
}catch(error){}
}
If you are getting a “Possible unhandled promise rejection” warning in your React Native app, it means that a promise was rejected, but the rejection was not handled. Promises in JavaScript are used to handle asynchronous operations, and they can either be resolved or rejected.
axios.post(URL+'/checkData',
{
usernameCheckAXIOS : username,
passwordCheckAXIOS : password,
})
.then((response)=>{
//... your code
})
.chatch(error => console.log(error)) // <-- add this line
The HTTP 404 Not Found response status code indicates that the server cannot find the requested resource
so verify your URL, should be invalid because it cannot be found.
[Axios error: Request failed with statis code 404] is an error URL not found.
Are you sure that the url URL+'/checkData' is valid ?

How can I make HTMX display a 403 error page returned from a hx-delete request?

In my project, when the web browser submits a hx-delete request, and the backend determines the user doesn't have the required permissions for that request, the backend returns a full 403 error page. By default HTMX ignores this response. I would like HTMX to instead display the full 403 error page.
How can I do this?
I solved my problem by adding this code to the page.
/***
* Swaps in the body of error pages returned from htmx requests
*/
document.addEventListener("htmx:beforeOnLoad", function (event) {
const xhr = event.detail.xhr
if (xhr.status == 500 || xhr.status == 403 || xhr.status == 404) {
event.stopPropagation() // Tell htmx not to process these requests
document.children[0].innerHTML = xhr.response // Swap in body of response instead
}
})

How can I fix an Axios interceptor causing property 'status' of undefined error

I have a selection to set permissions for elements to global or private. I'm using the Axios interceptor request to handle looking for the permissions field to have data and, if it does, stringify it. The problem is, it causes me to get a "TypeError: Cannot read property 'status' of undefined" when I attempt to reload the program at all. The only "fix" right now is to log out, remove the interceptor, log in, read it, and then run the check again.
Because of this, I can't even get to the home dashboard of the software. If I clear my cookies, I can go back to the login screen, but no further than that after attempting to log in.
Is there something I'm missing for it? below is the interceptor code. If more information or context is needed, please let me know.
export default {
install: (Vue) => {
Vue.$eventBus = new Vue();
Vue.axios.interceptors.response.use(response => {
return response.data;
}, async error => {
if (error.response.status === 401 && error.config.url != '/api/authentication/login') {
var config = await Vue.$configService.find();
window.location = config.accountPortalUrl;
return
}
console.log(error);
Vue.$eventBus.$emit('notifyUser', 'Uh oh, something went wrong!');
return Promise.reject(error);
});
Vue.axios.interceptors.request.use(
config => {
// check request method -> use post if many params
if (config.data.permissions) {
config.data.permissions = JSON.stringify(config.data.permissions);
}
console.log(config);
return config;
}
);
}
};
Looks like your service API is not responding, this might happen if the user is not authenticated . Your error is at line where you check (error.response.status). Its only possible to get an undefined response when the request was interrupted before response. Most probably if you check your browser network pannel you will see that the preflight check for this request causes a 401 network error. Hence because the preflight failed your actual response comes as undefined. You should sanity check first if your server responded with a response or not and then access the response status.
Something like this might help
if (error.response) {
// Request was made and the server responded successfully
// You can now de-structure the response object to get the status
console.log(error.response.status);
} else if (error.request) {
// request was made but not responded by server
console.log(error.request);
}
So, the answer ultimately was something extremely simple.
if (config.data.permissions)
needed to be
if (config.data && config.data.permissions)

How can I mock an http error response in dart?

So I'm doing some unit tests for my http provider.
In one of my tests I want to verify that when I do a POST call and I get an error response with status 409 I do then a call to PATCH and everything works.
This is my code
Future<IdentityResponse> _createUser(dynamic body) {
return http
.post(api, body: json.encode(body))
.catchError((err) {
return _isStatusCode(err, 409) ? _patchUser(body) : throw (err);
});
}
I'm using mockito, and tried first returning a Response like this:
when(http.post(argThat(startsWith(api)), body: anyNamed('body')))
.thenAnswer((_) async => Response("user exists", 409);
And it works... kind of. I catch the error, but then I can't get the status code, I get only the message 'user exists'
If I change to the structure that the backend returns, which is {"error": { "code": 409 }} and I do this:
when(http.post(argThat(startsWith(api)), body: anyNamed('body')))
.thenAnswer((_) async => Response(json.encode(fakeErrorResponse), 409);
Then my catch does not work anymore (??)
I tried then to return an error instead of a response, like this:
when(http.post(argThat(startsWith(api)), body: anyNamed('body')))
.thenAnswer((_) => Future.error(fakeErrorResponse));
Now my catch works again, but the error I get is an _ImmutableMap and I see no easy way to retrieve my data from there.
How can I mock an http error that returns the body that I want and not a simple String?
Thanks

How to handle Akka HTTP client response failure

Akka HTTP client requests return Future[HttpResponse] - how should one handle the Future failing? Just log an error or re-throw it to the supervisor?
Is there documentation of the type of errors that can be returned by thrown by the client (and hence automatically propagated to the supervisor ) as well as errors that can cause the Furure to fail.
It's matter of taste mostly. I typically convert Future[HttpResponse] to Future[Try[HttpResponse]] and then handle it as
response.flatMap { tryResp =>
tryResp match {
case Success(res) =>
res.status match {
case OK =>
// Unmarshal response here into Future[Something]
case Found =>
// Handle redirect by calling requestBlhBlah() again with anotehr URI
case _ =>
// I got status code I didn't expect so I wrap it along with body into Future failure
Unmarshal(res.entity).to[String].flatMap { body =>
Future.failed(new IOException(s"The response status is ${res.status} [${request.uri}] and response body is $body"))
}
}
case Failure(ex) =>
Future.failed(ex)
}
}
If you're using flow-based client you can also specify Decider to handle errors
val decider: Decider = {
case ex =>
ex.printStackTrace()
Supervision.Stop // Passes error down to subscriber
}
and then use it in either materializer
implicit val materializer = ActorMaterializer(ActorMaterializerSettings(system).withSupervisionStrategy(decider))(system)
or in per-flow basis via .withAttributes(ActorAttributes.supervisionStrategy(decider))
As per Future failure it's up to you how to handle it. You can convert failure to something else using recoverWith or log it in Future.onFailure.