Error: Uncaught (in promise): [object Object]

Viewed 20947
@Injectable()
class MyErrorHandler implements ErrorHandler {

  handleError(error) {
    // exception occured in some service class method.
    console.log('Error in MyErrorhandler - %s', error);
      if(error == 'Something went wrong'){
       //do this.
     }else{
      //do this thing.
    }
  }
}

When in some class' method throws an exception then, the MyErrorHandler class prints the error caught as Error in MyErrorhandler - Error: Uncaught (in promise): [object Object] Error: Something went wrong.

Question1: Why does the error displays as Error: Uncaught (in promise): [object Object]?

Question2: Due to the above message it will always read the else part even in the case of if(error == 'Something went wrong')of the code in any condition.How can I resolve this?

3 Answers

Try adding

if(error.message == 'Something went wrong'){
}

instead of only error. As error is an object.

is necesary your check the response in yours promise...

you have to capture resolve and reject...

generally this happens because the value of reject not is capture

for example

CREATE PROMISE...

promise= () => {
    return new Promise((resolve, reject) => {
      if (condition) {
         resolve(true);
      }else{
        reject(false);
      }
    });
}

And here capture ALL posible response in promise..

this.services.promise().then(
    (data) => {
       here capture your resolve
       },
    (err) => {
       here capture your resolve
    }
);

OR

 this.services.promise()
   .then((res) => {
       console.log('response in resolve = ', )});
    ).catch((err)=> {
      console.log('response in reject = ', err)
    })
import { Injectable, ErrorHandler, Injector } from '@angular/core';
import { AlertService } from './_alert.service';

@Injectable({
  providedIn: 'root'
})
export class ErroresService implements ErrorHandler {

  constructor(private sv_alert:AlertService) { }
  
  handleError(err:any) { 
    const message = err.message ? err.message: err.message.toString();
    this.sv_alert.AlertaMensajeError(`${ message }`);
  }
} 
Related