Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return values and not void|values from catch method

I’m using a service for making all webrequest like that:

@Injectable({
  providedIn: 'root'
})
export class WebService {

  auth_token: string;

  constructor(public config: ConfigService, public http: HttpClient, public router: Router) {
    // load token
    this.auth_token = localStorage.getItem("token") ? localStorage.getItem("token") as string : "";
  }

  public async get<T>(dir: string) {
    return await this.http.get<T>(this.config.config.backend.url + dir, { headers: { 'Authorization': `Bearer ${this.auth_token}`, 'Content-Type': 'charset=UTF-8' } }).toPromise();
  }
}

Then, in component, I’m doing like:

constructor(web: WebService) {
   web.get<MyObject[]>("obj").then(values => {
     for(let obj of values) {
        obj.doSomething();
     }
   });
}

I want to manage error more globally, to don’t have to duplicate code. It’s mostly to prevent wrong token/expired token/etc.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, I edited my service to have like this:

public async get<T>(dir: string) {
   return await this.http.get<T>(this.config.config.backend.url + dir, { headers: { 'Authorization': `Bearer ${this.auth_token}`, 'Content-Type': 'charset=UTF-8' } }).toPromise().catch(err => {
      // here manage all err status code
   });
}

But the catch method return Promise<void | T> and not Promise<T>. So, I have error on the then() method because the values variable can be void. Exact error is: Type 'void | MyObject[]' is not assignable to type 'MyObject[]'.

How can I fix it ?

>Solution :

Return a value in the catch. That can be an empty array for example, when getting a list.

.catch(err => {
  // here manage all err status code
  return [];
}

However, you need to define beforehand in that case, if the default value for the Promise is an empty array, an empty string, zero or whatever

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading