I am using the below methods to send data. I want to display an error response on my component. How can I console log error message in my component?
component.ts
signup(){
return this.loginservice.signupUser(this.model).subscribe(data => {
console.log(data.error);
});
}
service ts
signupUser(signupuserModel: any = {}):Observable<any>{
return this.http.post(`${this.signuouserurl}`,signupuserModel)
}
error message
In RxJS, subscribe() method can have 3 functions
next() if observable emits value.
error() if there's an error thrown from the Observable
complete() if the observable is completed.
What you need to do is to add an extra arrow function in your server call inside subscribe() method
public error: any;
signup() {
return this.loginservice.signupUser(this.model).subscribe(success => {
console.log(success);
}, error => { // second parameter is to listen for error
console.log(error);
this.error = error;
});
}
If you want to show the error in your component.html, you can use the interpolation {{ }}
component.html
<div class="error">{{ error }}</div>
try
signup() {
return this.loginservice.signupUser(this.model).subscribe(data => {
console.log(data);
}, err => {
console.log(err);
});
}
You can also use try-catch approach in following way
async signup() {
try {
let data = await this.loginservice.signupUser(this.model).toPromise();
console.log(data)
} catch (e) {
console.log(e);
}
}
However not all http codes raise exception
you can choose any method to display an error.. on of the best way is seprate the success and error response with following code (for this your http call must thrown an exception if not then you have to chose the second option )
signup() {
return this.loginservice.signupUser(this.model).subscribe(success => {
console.log(success);
}, error => {
console.log(error);
});
}
or you can write conditional code like
signup() {
return this.loginservice.signupUser(this.model).subscribe(success => {
console.log(data);
if(success.status == 406){ console.log("success")}
else { console.log("Error ") }
}
}
Related
component which is calling submitUser
this.someservice.submitUser(postData).subscribe((data) => {
this.viewUsers();
}, (err) => {
console.log('error in the component', err);
});
Here is the service file with submitUser function
public submitUser(reqBody ) {
return this.httpService.post('roles', reqBody, '/business/create')
.pipe(
catchError(
this.httpService.handleError())
);
}
and here is the httpService Post and handleError methods
public post<JSON>(url: string, body: any, param?: string, options?: IRequestOptions): Observable<JSON> {
return this.intercept(this.http.post<JSON>(this.getURLFromMethodName(url, param), body, this.requestOptions(options)));
}
handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error('error from httpclient', error); // log to console instead
throw throwError(new Error(error));
};
}
handleError adisplays the console error, I am trying to return/capture this error in my submitUser function in service.ts
How do i do that ? Any Inputs appreciated, Thanks
Your handleError() method returns an error observable along with logging the error to the console.
When some error occurs, the catchError operator takes that error and gives it to handleError() which in turn returns an error observable.
CASE 1: Returning the error
If you need to pass this error on to the subscriber, you don't have to do anything. The catchError operator is already taking care of it for you.
With the same code, let's say some component is consuming your service, then you can just write
someService.submitUser().subscribe((res) => {
\\ handle success
}, (err) => {
console.error(err); // Will print the error
});
Whenever the error occurs, the catchError is going to return the error observable back to its subscriber and it will go in the error function of the observer as shown in the code snippet above.
CASE 2: Handling the error
The catchError operator accepts a function that takes error as an argument. If you return another observable inside this instead of throwing an error, the subscriber won't get to know that the error had occurred, the success function of the observer will execute.
// Inside the service
public submitUser(reqBody ) {
return this.httpService.post('roles', reqBody, '/business/create')
.pipe(
catchError((err) => of([1,2,3]));
}
// Inside the component consuming the service
someService.submitUser().subscribe((res) => {
console.log(res) // Will print [1,2,3]
}, (err) => {
\\ handle error
});
I have the following code in my own async function that uses another imported function from module which is a custom wrap of axios inside try/catch block:
async function getCharacter (realmSlug, characterName) {
try {
const [{id, name, gender, faction, race, character_class, active_spec, realm, guild, level, last_login_timestamp, average_item_level, equipped_item_level}, {pets, unlocked_battle_pet_slots},{mounts}] = await Promise.all([
getCharacterSummary(realmSlug, characterName), -- custom axios instance
getCharacterPetsCollection(realmSlug, characterName),
getCharacterMountsCollection(realmSlug, characterName)
])
....
return result;
} catch (error) {
console.log(error.code);
if (error.response.status === 404 || error.response.status === 403) {
console.error(`${getCharacter.name},${characterName}#${realmSlug}`);
}
return { name: characterName, realm: realmSlug }
}
}
The problem is that if I use promise.all according to Stackoverflow 1,2 I can not handle errors. So the problem is when I call function to execute, my errors doesn't handle in (catch) block. At all. Even if I don't need print them, anyway I receive messages in console about 404 errors, but console.log(error.code) still gives me nothing. For example:
So is there any way to handle this annoying error messages in console somehow?
For example using .catch somewhere? Or using for await ... of or rxJS instead if it's possible?
Exporting function and using .catch
Even if I export this function getCharacter in another .js file and use the following code:
const getCharacter = require('./getCharacter');
let bulkCharacters = [{realmSlug, characterName},{realmSlug, characterName},... ,n] //array of characters for getCharacter request
const promises = bulkCharacters.map(async ({realmSlug, characterName}) => {
try {
return await getCharacter(realmSlug, characterName);
} catch (e) {
console.log(e)
}
});
let test = await Promise.all(promises)
.catch(function(arrayOfPromises, err) {
// log that I have an error, return the entire array;
console.log('A promise failed to resolve', err);
return arrayOfPromises;
})
.then(function(arrayOfPromises) {
console.log(arrayOfPromises)
})
;
console.log('stop')
I still receive errors in console, without triggering catch block inside getCharacter function or this file in which this function was imported and catch block is outside the function.
I try to call metetor method but it is throwing me error "Uncaught TypeError: Meteor.call is not a function" but when I try to call same in another file inside imports/api/some.js this works, meaning the call code is correct but it is working inside onSubmit why ? Here is github url
File : imports/ui/otp.js
onSubmit(e) {
e.preventDefault();
let otp = this.refs.otp.value.trim();
Meteor.call('find-otp', otp, (error, result) => {
if(error) {
console.log('otp error check', error);
} else {
console.log('otp res check', result);
}
});
}
File : imports/api/db.js
Meteor.methods({
'find-otp' (otp) {
// if(!this.userId) {
// throw new Meteor.Error('not-authorized');
// }
console.log('otpcheck', otp);
return true;
// return otp; // also I try this
}
});
Make sure you properly import Meteor:
import { Meteor } from 'meteor/meteor'
I am using below code to retrieve a value
try {
discountFbRef.orderByChild('discode').equalTo(code).on("value", function(snapshot) {
console.log('snapshot val discode', snapshot.val().discode);
if (snapshot.exists()) {
snapshot.forEach(function(data) {
$scope.discountApplicable.id = data.val().id;
});
} else {
console.log('It doesnt exist');
}
}, function(error) {
console.log(error);
});
} catch (error) {
console.log('error occured during search', error);
}
When there is value equal to the search string it's working fine. But when I try to find a keyword that doesn't exist in "discode", It throws
Uncaught TypeError: Cannot read property 'discode' of null
For some reason even though I try to catch the error with try-catch and error function I am not able to catch it.
I need a way to handle the error and show message that search string doesn't exist.
So, the functions that are passed to the second and third parameters of .on are called a callback functions. That means they might get called after (asynchronously) the code you've posted has executed. You'll want to move your try-catch inside of the callback function.
function handleValueSuccess(snapshot) {
try {
console.log('snapshot val discode', snapshot.val().discode);
if (snapshot.exists()) {
snapshot.forEach(function(data) {
$scope.discountApplicable.id = data.val().id;
});
} else {
console.log("It doesn't exist");
}
} catch (error) {
console.log('error occurred during search', error);
}
}
function handleValueError(error) {
console.log('error occurred on value', error);
}
discountFbRef
.orderByChild('discode')
.equalTo(code)
.on("value", handleValueSuccess, handleValueError);
I have two (multiple) async functions wrapped in an Observable and want to run them all together and check whenever one has an error or has completed. Here is what I do:
var observables = [];
observables.push(new Observable((observer:any) => {
async1(options, (error, info) => {
if (error) {
observer.error(error);
} else {
observer.next(info);
observer.complete();
}
});
}))
observables.push(new Observable((observer:any) => {
async2(options, (error, info) => {
if (error) {
observer.error(error);
} else {
observer.next(info);
observer.complete();
}
});
}))
Observable.forkJoin(observables).subscribe(
data => {
console.log(data);
},
error => {
console.log(error);
}
)
Now here is my problem... when both async functions complete successfully, it calls data =>{} and returns both results in an array.
If one of the two functions fails, it will call once error =>{} and that's it. I would like to listen to every error, how can I do that?
The default behaviour for operators combining multiple streams is to exit as soon as one of the stream emits an error notification. This is so because, per Rx grammar, errors are final, so it is generally assumed that the stream returned by the operator must fail eagerly.
One easy solution here is to do away with the error notification and replaces that with an error data structure inserted into a next notification.
So something like :
observables.push(new Observable((observer:any) => {
async1(options, (error, info) => {
if (error) {
observer.next({error});
} else {
observer.next({info});
observer.complete();
}
});
}))
Then in your subscribe :
Observable.forkJoin(observables).subscribe(
arrayData => arrayData.forEach(data => data.info? {
console.log(data.info);
} : {
console.log(data.error);
})
)