Error handling in Angular2 - asp.net-web-api

I'm working on an Angular 2 service returning data from a restful WebApi backend.
I'm trying to make it gracefully handle the service not being available however I'm getting unexpected information in the error responses.
Here's the code
update(fund, transactionId:string, showToastOnError: boolean, useCorrectUrl: boolean) {
let options = this.getStartCall();
options.headers.append("transaction-id", transactionId)
let url = fundsUrl + (useCorrectUrl ? "" : "breakTheUrl");
return this._http.put(url, JSON.stringify(fund), options)
.map(res => res.json())
//.retry(5)
.catch(errorResponse => {
let res = <Response>errorResponse;
let err = res.json();
let emsg = err ?
(err.error ? err.error : JSON.stringify(err)) :
(res.statusText || 'unknown error');
this._logger.log(emsg, "The fund was not updated", LogLevel.Error, showToastOnError);
return Observable.throw(emsg);
})
.finally(() => this._spinnerService.hide());
}
When I look at the network traffic I see the 404 error as expected.
My problem is in my catch function.
Here's the value's I'm seeing:
JSON.stringify(errorResponse)
{"_body":{"isTrusted":true},"status":200,"statusText":"Ok","headers":{},"type":3,"url":null}"
errorResponse.json()
bubbles: false
cancelBubble: false
cancelable: false
currentTarget: XMLHttpRequest
defaultPrevented: false
eventPhase: 2
isTrusted: true
isTrusted: true
lengthComputable: false
loaded: 0
path: Array[0]
position: 0
returnValue: true
srcElement: XMLHttpRequest
target: XMLHttpRequest
timeStamp: 1460990458693
total: 0
totalSize: 0
type: "error"
__proto__: XMLHttpRequestProgressEvent
Am I doing something wrong here or is this a bug in Angular2 beta 15?

Most of time, you have such a value for an error when the onerror callback is called on the underlying XHR object. See this line in the source code: https://github.com/angular/angular/blob/master/modules/angular2/src/http/backends/xhr_backend.ts#L70.
That said, it shouldn't occur for a 404 status code but rather on an error like net::ERR_NAME_NOT_RESOLVED.
404 status code is handled by the onload callback: https://github.com/angular/angular/blob/master/modules/angular2/src/http/backends/xhr_backend.ts#L37.
I made a test with the beta15 and I can't reproduce your problem.
See this plunkr: https://plnkr.co/edit/SB3KLZlbJT3wm9ATAE0R?p=preview.

Related

Lambda#Edge function result failed validation

I have a lambda#edge in Viewer Request that is generating this error:
ERROR Validation error: Lambda function result failed validation, the function tried to add read-only header, headerName : Transfer-Enoding.
I tried to return this event in case of redirection:
const response = {
status: '301',
statusDescription: 'Found',
headers: {
'location': [{
key: 'location',
value: 'https://test.com'
}]
}
}
callback(null, response)
I also tried keeping the same event but I get the same error
const response = event.Records[0].cf.response;
response.status = 301;
response.statusDescription = 'Found';
response.headers['location'] = [{ key: 'Location', value:'https://www.test.com'}];
Cqn someone tells me how to fix this ?
PS: Even requests that pass by this lambda and doesnt verify the redirection condition result in this error also.

Neither onNext, nor onError is called when Angular HttpClient POST receives in 500

I am observing something that I cannot see/explain. I did talk to a second pair of eyes and did my due diligence googling. What am I missing - as the title says, onNext and onError aren't called, but onComplete is when back end returns HTTP500 (endpoint throws 500 for the purpose of testing angular error handling). Why?
Service:
delete(item: Item): Observable<any> {
return this.http.post(this.url("delete"), item, { headers: this.header });
}
Component:
this.itemDataService.delete(this.item)
.subscribe(
() => {
alert("result");
..;
},
err => {
alert("Error");
},
() => {
alert("complete");
...;
}
);
you probably have an interceptor swallowing your errors somewhere.. only way this could happen if that's the native http client.

Fineuploader possible solution to force header return true if default server will not return following JSON Data

Not sure if it's possible to force fineuploader to fire true success upload in anyway. im facing the issue of submitting form to a url "http://119.29.222.368:8991/upload"(sample ip due to P&C) where it will return only Status : "OK" without Success : true.
Following is my code, pretty sure that it successfully submitted, but my UI will get error due to the API is not returning the value success.
var uploader = new qq.FineUploader({
element: document.getElementById("uploader"),
cors: {
allowXdr: 'true',
expected:'true'
},
request: {
method:'POST',
// endpoint: '/upload',
endpoint: 'http://119.29.222.368:8991/upload',
forceMultipart:'true',
inputName:'filename',
params: {
'token': <%- JSON.stringify(token) %>,
'path':"/images/feed/"
}
}
})
This was originally requested in github.com/FineUploader/fine-uploader/issues/1325. Follow the linked pull request at the end of that issue for updates. – Ray Nicholus 20 hours ago

Angular2 post request despite a XMLHttRequest error

I send a request to a remote API. It takes a little time for API to proceed on its side.
After this little waiting time, i can see in network tab a HTTP 200. In the response, I got the proper intended information. Everything on the API side works fine.
BIT on the console, I can see I encountered a XMLHttpRequest Error.
Why, especially if I have a XMLHttpRequest Error, the POST is completed with 200? Shouldn't it be "blocked" by Angular2?
The unintended result is: my file is correctly uploaded and handled by the API, but in Angular2, it triggers the ERROR part of my call.
If I use https://resttesttest.com/ for example, it seems to encounter the same error but it doesn't finalize the POST:
Oh no! Javascript returned an
HTTP 0 error. One common reason this might happen is that you
requested a cross-domain resource from a server that did not include
the appropriate CORS headers in the response.
Angular 2 Code for this call
this.http
.post(this.documentUploadAPIUrl, formData, options)
.subscribe(
res => {
this.responseData = res.json();
console.log(this.responseData);
console.log('Uploaded a blob or file!');
},
error => {
console.log('Upload failed! Error:', error);
}
);
try to set withCredential attribute of xmlHttpRequest to true, this will send credentials managed by the browser, in angular 2 you can do like this
import { RequestOptions } from '#angular/http';
this.http
.post(this.documentUploadAPIUrl, formData, this.post_options)
.subscribe(
res => {
this.responseData = res.json();
console.log(this.responseData);
console.log('Uploaded a blob or file!');
},
error => {
console.log('Upload failed! Error:', error);
}
);
post_options() {
return new RequestOptions({ method: 'post', withCredentials : true });
}

Angular Resource Error Handling : How can I treat a success : false that comes from a resource?

Let's say I have an angular service that has this method:
this.query = function(params, successFn, errorFn) {
return $resource(backendUrl + '/myresource.json')
.query(params, successFn, errorFn);
};
Sometimes the rest API fails, so the errorFn is called. However, sometimes I might be sending invalid parameters and the Rest API would send a HTTP 200 with success : false. I know this is a bad practice but since the API is not to be changed, I'm left handling the error in the success callback.
As you may know, the success callback will always give me an array, so the JSON response :
{
'message' : 'invalid parameter x',
'success' : false
}
Would be exposed as the first parameter in the successFn as :
[ { 0 : 'i', '1' : 'n', '2' : 'v' .... }, {....} ]
Is there any way to get access to the original content returned from the API?
you can use $http instead of resource
// $http returns a promise, which has a then function, which also returns a promise
var promise = $http({
url: url,
method: "GET",
params: params
}).then(function (response) {
//do what you want to do with the response here
//to see what response contains print JSON.stringify(response)
});

Resources