2

I trying to catch errors in http post, but it's showing this error:

TypeError: error.json is not a function

I didn't find anything on google.

I followed the example on Angular.io site.

enter image description here

My code:

 import {Observable} from 'rxjs/Observable';

// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

//import 'rxjs/add/operator/catch';

@Injectable()
export class EmpresasCrudService {


    constructor(private _http: Http) {
    }

  //  public allItems;
   // public _qtd;

     postHttpEmpresas(endpoint_url, data): Observable<Response> {
         let body = JSON.stringify(data);

         let headers = new Headers({'Accept': 'application/json' });
         headers.append('Content-Type', 'application/json');
         let options = new RequestOptions({ headers: headers });

        return this._http.post(endpoint_url, body, options)
                        .map(res => res.json())
                        .catch(this.handleError);
    }

private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

EDIT: when I put:

postHttpEmpresas(endpoint_url, data): Observable<Response> {
         let body = JSON.stringify(data);

         let headers = new Headers({'Accept': 'application/json' });
         headers.append('Content-Type', 'application/json');
         let options = new RequestOptions({ headers: headers });

        return this._http.post(endpoint_url, body, options)
                        .map(res => res.json())
                        .catch(err => this.handleError(err));
    }

private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
    try {
        errMsg = error.json();
    } catch (e) {
        // No content response..
        errMsg = null;
    }
}
    console.log(errMsg);
    return Observable.throw(errMsg);
  }

it's showing the error in console.log but until give me a error: enter image description here

1 Answer 1

1

Calling Response#json() will throw an error if response does not have a body (status 204 - No Content response for example). If you don't know whether the error response has a body or not, a way to go would be to try/catch extracting the response content as follows:

if (error instanceof Response) {
    try {
        body = error.json();
    } catch (e) {
        // No content response..
        body = null;
    }
}
Sign up to request clarification or add additional context in comments.

14 Comments

I edit my question with the result of your answer... I don't know if i'm doing right
Yes, that's the concept I was pointing to. Do you still see your error? Btw you shouldn't have updated your original question, can you return the original question so the original context is kept for future users?
Also, error.json() will return a body object, I guess you need something like : let mssg = error.json().error;, or maybe: let mssg = error.json().errorMessage; ?
I put this 2 ways and, error: TypeError: error.json is not a function at SafeSubscriber._error (empresas-create.component.ts:300) at SafeSubscriber.__tryOrUnsub (Subscriber.js:223) at SafeSubscriber.error (Subscriber.js:184) at Subscriber._error (Subscriber.js:128) at Subscriber.error (Subscriber.js:102) at CatchSubscriber.error (catch.js:55) at MapSubscriber.Subscriber._error (Subscriber.js:128) at MapSubscriber.Subscriber.error (Subscriber.js:102) at XMLHttpRequest.onLoad (xhr_backend.js:77) at ZoneDelegate.invokeTask (zone.js:265)
I don't know what to do
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.