Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - How to convert Error Response to Error Object?

I want to log exceptions generated in typescript to a log file (text file). I want to log information like description,message,name,number,stack. I have written Model, API Controller and logic to write the data into text file.

However I want to map Error Response generated after get, post,put operation in typescript. I have written below Interface

export interface TypeScriptException {
    Description: string;
    Message: string;
    Name: string;
    Number: string;
    ErrorStack: string;
}

When handleError method is called after Post in below example, how do I assign values from Error Response to my TypeScriptException object?

post(url: string, model: any): Observable<any> {

    let body = JSON.stringify(model);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this._http.post(url, body, options)
        .map((response: Response) => <any>response.json())
        .catch(this.handleError);
}

private handleError(error: Response) {

    let typeScriptException: TypeScriptException;

    //What to do here

}
like image 788
captainsac Avatar asked Aug 09 '26 13:08

captainsac


1 Answers

In case of error, you get an instance of type HttpErrorResponse. You can extract fields from this instance and assign it to the typeScriptException variable that you've defined. You will have to leverage the details that are provided in this instance and set the fields on typeScriptException accordingly.

Here's what an instance of HttpErrorResponse looks like:

enter image description here

Keeping all the fields it has in mind, you can assign some of them to your typeScriptException, something along the lines of this:

private handleError(error: HttpErrorResponse) {
  let typeScriptException: TypeScriptException;
  let { message, name, ok, status, statusText, url } = error;
  //What to do here?
  typeScriptException = {
    Description: `${name} - ${message}`, // OR SOMETHING
    Message: message
    Name: name,
    Number: status, // OR SOMETHING
    ErrorStack: statusText // OR SOMETHING
  }
}
like image 54
SiddAjmera Avatar answered Aug 12 '26 10:08

SiddAjmera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!