Angular 2 RC5 http error handling - http

I am new in Angular 2, in my Angular 2 project I create API call service that return json data.
this._http.post(this.url, body, options)
.map(response => response.json())
.catch(this.handleError);
Let say this service return 401 Http Response unauthorized and I tried get the status error, so I can redirect to Login Page and show error message
.subscribe(
login => this.login=login,
error => this.errorMessage = <any>error);
}
but why response code did not throw as error, and only show result
Failed to load resource: the server responded with a status of 401 (Unauthorized) and end the task ?
when I debug the code, the result generated in this line code
this.invoke = function () {
try {
return zone.runTask(self, this, arguments);
}
finally {
drainMicroTaskQueue();
}
};
}
any suggestion ?
Thank You

Related

Changing the default exception message in Axios

When hitting an HTTP error, Axios only states the HTTP status code in the thrown exception message. I want the exception message to include the request URL, too.
I tried to implement what I want using the following interceptor:
axios.interceptors.response.use(
response => response,
error => {
throw `HTTP ${error.response.status} by ${error.request.url}`;
}
);
The error callback doesn't get triggered upon HTTP errors. Any ideas?
Try to use Promise.reject to replace throw.
The following code works for me. Tested in Chrome.
axios.interceptors.response.use(
function (response) {
return response;
},
function (error) {
return Promise.reject(`HTTP ${error.response.status} by ${error.response.config.url}`);
});
Also, you can simply catch the exception like -
let res = await axios.post(...)
.catch(error => {
console.log(error.response);
console.log(error.request);
});
You have access to all the error details as in interceptor.

Grab response message from .NET Core API with ky

I use ky package for sending HTTP requests to web api. Everything works except handling error messages.
Let me show you my source code:
// api method
[HttpPost("Test")]
public async Task<IActionResult> Test([FromBody] TestViewModel model)
{
if(model.Test)
{
return StatusCode(StatusCode.Status200OK, "Success message");
}
else
{
return StatusCode(StatusCodes.Status500InternalServerError, "Error message");
}
}
My aim is get and display Success message or Error message text on the frontend.
Client side:
//webclient.js
import ky from "ky";
export const webclient = ky.create({
prefixUrl: "http://localhost:62655/api",
});
Firing API call:
//testAPI.js
import { webclient } from '../../common/webclient';
const result = await webclient.post('Order/Test', { json: { ...model } }).json();
console.log(result);
If the status code is equal to 200 the message (Success message) show in console properly, but for 500 (or 400, or any else) console remains empty.
DevTools confirm that API returns 500 status code with message Error message so it's not an API problem.
The question is: how can I obtain an error message with ky?
The ky library doesn't seem very mature but I did find this issue thread which might help ~ https://github.com/sindresorhus/ky/issues/107#issuecomment-476048453
I would strongly suggest you just stick to vanilla fetch where you're in full control of handling the response text if required
const response = await fetch("http://localhost:62655/api/Order/Test", {
method: "POST",
headers: { "Content-type": "application/json" },
body: JSON.stringify({ ...model })
})
if (!response.ok) {
throw new Error(`${response.status}: ${await response.text()}`)
}
console.log(await response.json())

angular2 wait for error http response

I have a problem with angular2 http response.
I want to catch the error in my component.
How does my app work.
In my Component, I Call a function in a personal service :
var response = this.apiUser.login(username, password);
alert(response);
In my Service, I try to auth :
this.http.post(this.httpApiAdress + '/' + this.httpUserAutenticate, body, { headers: contentHeaders })
.subscribe(
response => {
localStorage.setItem('id_token', response.json().token);
this.router.navigate(['home']);
},
error => {
return error.json();
},
() => { }
);
When the auth is ok, all work fine. But when the Auth fail, i can't catch the response in my Component.
(Its undefinied because the alert is executed before the http call...)
Can u help me please !!! (It was working when all the code was only in my Component, but I wanted to slip my code...)
Ty.
Return the observable by using map() instead of subscribe()
return this.http.post(this.httpApiAdress + '/' + this.httpUserAutenticate, body, { headers: contentHeaders })
.map(
response => {
localStorage.setItem('id_token', response.json().token);
this.router.navigate(['home']);
},
);
and then use subscribe where you want to execute code when the response or error arrives
var response = this.apiUser.login(username, password)
.subscribe(
response => alert(response),
error => alert(error),
);

handling server error response along with data in angular 2 using HTTP observable

This is regarding handling server response in angular2
As i understand,
1. server response code 200, 201 etc will make success response
2. while server response 400, 401, 500 etc will make error response
3. if response is success, then it will goto map function, from there we can return the data or modify it.
4. if response is error, then it will go to catch function, from there we will can return observable or throw the observable.
My question is if server returned error response code along with error data, then how to capture that data.
i.e suppose i am sending below data from server
success response
status: 200
msg: "successfully loggedin"
error response
status: 400
msg: "userid and password is wrong"
Here i am able to get or handle success data but not the error data,because in catch function, only error object is getting passed and that error object only contain response code from server, not the response data
return this.http.get('/login')
.map( (res: Response) => res.json().data )
.catch( (error: any) => {
return Observable.throw( new Error("error occured"+error.status));
})
Update:
don't put return in map and catch function.
Below is updated code
return this.http.get('/login')
.map( ( successRes: Response) => {
res.json().data
)}
.catch( ( errorRes: Response ) => {
Observable.throw( errorRes.json().data );
})
Original:
Actually solution was very simple, response data itself is attached to first argument, its just like normal response as in the case of success response.
Just needed to add json() call to response error object to convert the json to js object, something like this.
return this.http.get('/login')
.map( ( successRes: Response) => {
return res.json().data
)}
.catch( ( errorRes: Response ) => {
return Observable.throw( errorRes.json().data );
})
You don't have to .catch() it!
If your server sends the correct message, just subscribe that Observable!
yourLoginService.LogInFunction().subscribe(
successData => console.log(successData),
errData => console.log(errData)
);

Proper error handling for Angular 2 http result [duplicate]

This question already has answers here:
Angular2 handling http response
(3 answers)
Closed 6 years ago.
I've been using the http error handling strategy used in the angular.io documentation:
getHeroes () {
return this.http.get(this._heroesUrl)
.map(res => <Hero[]> res.json().data)
.catch(this.handleError);
}
private handleError (error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
In some scenarios, instead of a JSON response I will receive a 204 status code (No Data). In this case, the error handler doesn't get invoked until failing to parse the result via res.json(), so the error passed to handleError is "error.json is not a function".
How can I interrogate the response stream to check for a 200 (OK) status code or a response header content-type of "application/json", and signal an error handler with a more relevant error message?
http .get('Some Url') .map(res => {
// If request fails, throw an Error that will be caught
if(res.statu != 200) {
throw new Error('This request has failed ' + res.status); } // If everything went fine, return the response
else {return res.json();
} })
This may help you.
This is just for understanding how to use the status from the response, you can modify according to your requirement.
Error is thrown only for non 200 code check this commit

Resources