Angular 7 - How to capture 500 server error on http.post when returning a new Promise? Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!ECMAScript 6 Chaining Promiseswhy I got this.http.get(…).subscribe is not a function in angular2error promise unresolbed angular 2Effectively capturing Angular 2 HTTP ErrorsAngular2 : HTTP Observables flow is not clearcatching a promise error wrapped into an observable - angular 2Component update/render being triggeredangular 2 - file upload using formdata to an express server - using multerNode JS Promise TypeError: Cannot read property 'then' of undefinedIssue with route resolver

Retract an already submitted recommendation letter (written for an undergrad student)

Second order approximation of the loss function (Deep learning book, 7.33)

How would I use different systems of magic when they are capable of the same effects?

How to count in linear time worst-case?

A Paper Record is What I Hamper

Map material from china not allowed to leave the country

"Rubric" as meaning "signature" or "personal mark" -- is this accepted usage?

Raising a bilingual kid. When should we introduce the majority language?

Are these square matrices always diagonalisable?

My admission is revoked after accepting the admission offer

Is Bran literally the world's memory?

Can I criticise the more senior developers around me for not writing clean code?

Why did Israel vote against lifting the American embargo on Cuba?

What is /etc/mtab in Linux?

All ASCII characters with a given bit count

Can you stand up from being prone using Skirmisher outside of your turn?

What is it called when you ride around on your front wheel?

How can I wire a 9-position switch so that each position turns on one more LED than the one before?

Why does the Cisco show run command not show the full version, while the show version command does?

How would this chord from "Rocket Man" be analyzed?

What is ls Largest Number Formed by only moving two sticks in 508?

What was Apollo 13's "Little Jolt" after MECO?

Married in secret, can marital status in passport be changed at a later date?

PIC mathematical operations weird problem



Angular 7 - How to capture 500 server error on http.post when returning a new Promise?



Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!ECMAScript 6 Chaining Promiseswhy I got this.http.get(…).subscribe is not a function in angular2error promise unresolbed angular 2Effectively capturing Angular 2 HTTP ErrorsAngular2 : HTTP Observables flow is not clearcatching a promise error wrapped into an observable - angular 2Component update/render being triggeredangular 2 - file upload using formdata to an express server - using multerNode JS Promise TypeError: Cannot read property 'then' of undefinedIssue with route resolver



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm getting a 500 server error (which I expect) but my current implementation does not capture the error. Instead of capturing the error in the component and handling it, the app produces a 500 server error in the browser console and the execution gets halted and the loading spinner remains. I'm having a hard time figuring this out. I've restructured the promise a few different ways with no luck.



** Update **



I updated the service to use reject in the promise but that still did not work.



Component code



save() 
this.loading = true; this.itemService.updateItems(this.updatedItems, this.activeCompanyId).then(() =>
this.loading = false;
).catch((err) =>
console.log("Error updating items", err);
);



Service code



updateItems(items:Item[], companyId) 
let headers = new HttpHeaders()
.set("Content-Type", "application/json")
.set("CompanyId", companyId);

return new Promise((resolve, reject) =>
this.http.post(`$this._config.API_URL`, items, headers ).subscribe(
data =>
resolve(data);
,
err =>
console.log('Error updating items', err);
reject(err);

);
);










share|improve this question
























  • Just a question, there is a reason that you use Promises instead of working with Observables that are natively used in Angular ?

    – Martin Paucot
    Mar 22 at 16:03












  • No particular reason other than then using what I already knew. I'm more than happy to re-factor to use an Observable instead just not sure how to do it properly. Originally when I chose to use Promises I went with what at the time I felt was the safer option for the requests to behave as I expected.

    – Smooth
    Mar 22 at 16:06

















0















I'm getting a 500 server error (which I expect) but my current implementation does not capture the error. Instead of capturing the error in the component and handling it, the app produces a 500 server error in the browser console and the execution gets halted and the loading spinner remains. I'm having a hard time figuring this out. I've restructured the promise a few different ways with no luck.



** Update **



I updated the service to use reject in the promise but that still did not work.



Component code



save() 
this.loading = true; this.itemService.updateItems(this.updatedItems, this.activeCompanyId).then(() =>
this.loading = false;
).catch((err) =>
console.log("Error updating items", err);
);



Service code



updateItems(items:Item[], companyId) 
let headers = new HttpHeaders()
.set("Content-Type", "application/json")
.set("CompanyId", companyId);

return new Promise((resolve, reject) =>
this.http.post(`$this._config.API_URL`, items, headers ).subscribe(
data =>
resolve(data);
,
err =>
console.log('Error updating items', err);
reject(err);

);
);










share|improve this question
























  • Just a question, there is a reason that you use Promises instead of working with Observables that are natively used in Angular ?

    – Martin Paucot
    Mar 22 at 16:03












  • No particular reason other than then using what I already knew. I'm more than happy to re-factor to use an Observable instead just not sure how to do it properly. Originally when I chose to use Promises I went with what at the time I felt was the safer option for the requests to behave as I expected.

    – Smooth
    Mar 22 at 16:06













0












0








0








I'm getting a 500 server error (which I expect) but my current implementation does not capture the error. Instead of capturing the error in the component and handling it, the app produces a 500 server error in the browser console and the execution gets halted and the loading spinner remains. I'm having a hard time figuring this out. I've restructured the promise a few different ways with no luck.



** Update **



I updated the service to use reject in the promise but that still did not work.



Component code



save() 
this.loading = true; this.itemService.updateItems(this.updatedItems, this.activeCompanyId).then(() =>
this.loading = false;
).catch((err) =>
console.log("Error updating items", err);
);



Service code



updateItems(items:Item[], companyId) 
let headers = new HttpHeaders()
.set("Content-Type", "application/json")
.set("CompanyId", companyId);

return new Promise((resolve, reject) =>
this.http.post(`$this._config.API_URL`, items, headers ).subscribe(
data =>
resolve(data);
,
err =>
console.log('Error updating items', err);
reject(err);

);
);










share|improve this question
















I'm getting a 500 server error (which I expect) but my current implementation does not capture the error. Instead of capturing the error in the component and handling it, the app produces a 500 server error in the browser console and the execution gets halted and the loading spinner remains. I'm having a hard time figuring this out. I've restructured the promise a few different ways with no luck.



** Update **



I updated the service to use reject in the promise but that still did not work.



Component code



save() 
this.loading = true; this.itemService.updateItems(this.updatedItems, this.activeCompanyId).then(() =>
this.loading = false;
).catch((err) =>
console.log("Error updating items", err);
);



Service code



updateItems(items:Item[], companyId) 
let headers = new HttpHeaders()
.set("Content-Type", "application/json")
.set("CompanyId", companyId);

return new Promise((resolve, reject) =>
this.http.post(`$this._config.API_URL`, items, headers ).subscribe(
data =>
resolve(data);
,
err =>
console.log('Error updating items', err);
reject(err);

);
);







angular promise http-post






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 15:49







Smooth

















asked Mar 22 at 15:35









SmoothSmooth

4521929




4521929












  • Just a question, there is a reason that you use Promises instead of working with Observables that are natively used in Angular ?

    – Martin Paucot
    Mar 22 at 16:03












  • No particular reason other than then using what I already knew. I'm more than happy to re-factor to use an Observable instead just not sure how to do it properly. Originally when I chose to use Promises I went with what at the time I felt was the safer option for the requests to behave as I expected.

    – Smooth
    Mar 22 at 16:06

















  • Just a question, there is a reason that you use Promises instead of working with Observables that are natively used in Angular ?

    – Martin Paucot
    Mar 22 at 16:03












  • No particular reason other than then using what I already knew. I'm more than happy to re-factor to use an Observable instead just not sure how to do it properly. Originally when I chose to use Promises I went with what at the time I felt was the safer option for the requests to behave as I expected.

    – Smooth
    Mar 22 at 16:06
















Just a question, there is a reason that you use Promises instead of working with Observables that are natively used in Angular ?

– Martin Paucot
Mar 22 at 16:03






Just a question, there is a reason that you use Promises instead of working with Observables that are natively used in Angular ?

– Martin Paucot
Mar 22 at 16:03














No particular reason other than then using what I already knew. I'm more than happy to re-factor to use an Observable instead just not sure how to do it properly. Originally when I chose to use Promises I went with what at the time I felt was the safer option for the requests to behave as I expected.

– Smooth
Mar 22 at 16:06





No particular reason other than then using what I already knew. I'm more than happy to re-factor to use an Observable instead just not sure how to do it properly. Originally when I chose to use Promises I went with what at the time I felt was the safer option for the requests to behave as I expected.

– Smooth
Mar 22 at 16:06












3 Answers
3






active

oldest

votes


















1














In case of an error, you want to reject the Promise:



updateItems(items:Item[], companyId) 
let headers = new HttpHeaders()
.set("Content-Type", "application/json")
.set("CompanyId", companyId);

return new Promise((resolve, reject) =>
this.http.post(`$this._config.API_URL`, items, headers ).subscribe(
data =>
resolve(data);
,
err =>
console.log('Error updating items', err);
reject(err);

);
);






share|improve this answer























  • I tried that and it didn't work :( I updated the question to reflect the usage of reject in the promise. Nothing gets logged out except the 500 server error in the browser console and the spinner remains.

    – Smooth
    Mar 22 at 15:45



















0














I think the solution to your issue might be the http interceptor: https://angular.io/api/common/http/HttpInterceptor



create a file (for example error-interceptor.ts and inside add the following (be sure to add this class to your module's providers)



@Injectable()
export class ErrorInterceptor implements HttpInterceptor
constructor()

intercept(req: HttpRequest<any>, next: HttpHandler)
return next.handle(req).pipe(
catchError((errorResponse: HttpErrorResponse) =>
console.error(errorResponse.error);
)
);





providers: [
provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true
],


As the name implies, you can now "intercept" all incoming http responses and check for an error. Depending on what you're using to send back your response on the backside, your response after an error (this is express).



res.status(500).json( message: "Server Boo-Boo" );


Then you can access the message with:



errorResponse.error.message;





share|improve this answer























  • The HttpInterceptor will catch every response, it's not the question here.

    – Martin Paucot
    Mar 22 at 16:01











  • It will only catch all of them if you want it to. They can easily be filtered based on response code, message or anything else.

    – docb45
    Mar 22 at 16:44











  • I already had an interceptor in place for authentication so I filtered it based on response code 500

    – Smooth
    Mar 22 at 16:54


















0














I was able to solve the issue by using an HttpIntercepter



import Injectable from "@angular/core";
import
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse
from "@angular/common/http";
import Observable, of, throwError from "rxjs";
import catchError from 'rxjs/operators';


@Injectable()
export class AuthInterceptor implements HttpInterceptor

constructor(public auth: AuthService, public navService: NavService)

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
let request = req.clone(
withCredentials: true
);

return next.handle(request).pipe(catchError((err, caught) =>
if (err instanceof HttpErrorResponse)
if (err.status === 500)
return throwError(err)


return of(err);
) as any);







share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55303128%2fangular-7-how-to-capture-500-server-error-on-http-post-when-returning-a-new-pr%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    In case of an error, you want to reject the Promise:



    updateItems(items:Item[], companyId) 
    let headers = new HttpHeaders()
    .set("Content-Type", "application/json")
    .set("CompanyId", companyId);

    return new Promise((resolve, reject) =>
    this.http.post(`$this._config.API_URL`, items, headers ).subscribe(
    data =>
    resolve(data);
    ,
    err =>
    console.log('Error updating items', err);
    reject(err);

    );
    );






    share|improve this answer























    • I tried that and it didn't work :( I updated the question to reflect the usage of reject in the promise. Nothing gets logged out except the 500 server error in the browser console and the spinner remains.

      – Smooth
      Mar 22 at 15:45
















    1














    In case of an error, you want to reject the Promise:



    updateItems(items:Item[], companyId) 
    let headers = new HttpHeaders()
    .set("Content-Type", "application/json")
    .set("CompanyId", companyId);

    return new Promise((resolve, reject) =>
    this.http.post(`$this._config.API_URL`, items, headers ).subscribe(
    data =>
    resolve(data);
    ,
    err =>
    console.log('Error updating items', err);
    reject(err);

    );
    );






    share|improve this answer























    • I tried that and it didn't work :( I updated the question to reflect the usage of reject in the promise. Nothing gets logged out except the 500 server error in the browser console and the spinner remains.

      – Smooth
      Mar 22 at 15:45














    1












    1








    1







    In case of an error, you want to reject the Promise:



    updateItems(items:Item[], companyId) 
    let headers = new HttpHeaders()
    .set("Content-Type", "application/json")
    .set("CompanyId", companyId);

    return new Promise((resolve, reject) =>
    this.http.post(`$this._config.API_URL`, items, headers ).subscribe(
    data =>
    resolve(data);
    ,
    err =>
    console.log('Error updating items', err);
    reject(err);

    );
    );






    share|improve this answer













    In case of an error, you want to reject the Promise:



    updateItems(items:Item[], companyId) 
    let headers = new HttpHeaders()
    .set("Content-Type", "application/json")
    .set("CompanyId", companyId);

    return new Promise((resolve, reject) =>
    this.http.post(`$this._config.API_URL`, items, headers ).subscribe(
    data =>
    resolve(data);
    ,
    err =>
    console.log('Error updating items', err);
    reject(err);

    );
    );







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 22 at 15:41









    slothsloth

    76k15129174




    76k15129174












    • I tried that and it didn't work :( I updated the question to reflect the usage of reject in the promise. Nothing gets logged out except the 500 server error in the browser console and the spinner remains.

      – Smooth
      Mar 22 at 15:45


















    • I tried that and it didn't work :( I updated the question to reflect the usage of reject in the promise. Nothing gets logged out except the 500 server error in the browser console and the spinner remains.

      – Smooth
      Mar 22 at 15:45

















    I tried that and it didn't work :( I updated the question to reflect the usage of reject in the promise. Nothing gets logged out except the 500 server error in the browser console and the spinner remains.

    – Smooth
    Mar 22 at 15:45






    I tried that and it didn't work :( I updated the question to reflect the usage of reject in the promise. Nothing gets logged out except the 500 server error in the browser console and the spinner remains.

    – Smooth
    Mar 22 at 15:45














    0














    I think the solution to your issue might be the http interceptor: https://angular.io/api/common/http/HttpInterceptor



    create a file (for example error-interceptor.ts and inside add the following (be sure to add this class to your module's providers)



    @Injectable()
    export class ErrorInterceptor implements HttpInterceptor
    constructor()

    intercept(req: HttpRequest<any>, next: HttpHandler)
    return next.handle(req).pipe(
    catchError((errorResponse: HttpErrorResponse) =>
    console.error(errorResponse.error);
    )
    );





    providers: [
    provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true
    ],


    As the name implies, you can now "intercept" all incoming http responses and check for an error. Depending on what you're using to send back your response on the backside, your response after an error (this is express).



    res.status(500).json( message: "Server Boo-Boo" );


    Then you can access the message with:



    errorResponse.error.message;





    share|improve this answer























    • The HttpInterceptor will catch every response, it's not the question here.

      – Martin Paucot
      Mar 22 at 16:01











    • It will only catch all of them if you want it to. They can easily be filtered based on response code, message or anything else.

      – docb45
      Mar 22 at 16:44











    • I already had an interceptor in place for authentication so I filtered it based on response code 500

      – Smooth
      Mar 22 at 16:54















    0














    I think the solution to your issue might be the http interceptor: https://angular.io/api/common/http/HttpInterceptor



    create a file (for example error-interceptor.ts and inside add the following (be sure to add this class to your module's providers)



    @Injectable()
    export class ErrorInterceptor implements HttpInterceptor
    constructor()

    intercept(req: HttpRequest<any>, next: HttpHandler)
    return next.handle(req).pipe(
    catchError((errorResponse: HttpErrorResponse) =>
    console.error(errorResponse.error);
    )
    );





    providers: [
    provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true
    ],


    As the name implies, you can now "intercept" all incoming http responses and check for an error. Depending on what you're using to send back your response on the backside, your response after an error (this is express).



    res.status(500).json( message: "Server Boo-Boo" );


    Then you can access the message with:



    errorResponse.error.message;





    share|improve this answer























    • The HttpInterceptor will catch every response, it's not the question here.

      – Martin Paucot
      Mar 22 at 16:01











    • It will only catch all of them if you want it to. They can easily be filtered based on response code, message or anything else.

      – docb45
      Mar 22 at 16:44











    • I already had an interceptor in place for authentication so I filtered it based on response code 500

      – Smooth
      Mar 22 at 16:54













    0












    0








    0







    I think the solution to your issue might be the http interceptor: https://angular.io/api/common/http/HttpInterceptor



    create a file (for example error-interceptor.ts and inside add the following (be sure to add this class to your module's providers)



    @Injectable()
    export class ErrorInterceptor implements HttpInterceptor
    constructor()

    intercept(req: HttpRequest<any>, next: HttpHandler)
    return next.handle(req).pipe(
    catchError((errorResponse: HttpErrorResponse) =>
    console.error(errorResponse.error);
    )
    );





    providers: [
    provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true
    ],


    As the name implies, you can now "intercept" all incoming http responses and check for an error. Depending on what you're using to send back your response on the backside, your response after an error (this is express).



    res.status(500).json( message: "Server Boo-Boo" );


    Then you can access the message with:



    errorResponse.error.message;





    share|improve this answer













    I think the solution to your issue might be the http interceptor: https://angular.io/api/common/http/HttpInterceptor



    create a file (for example error-interceptor.ts and inside add the following (be sure to add this class to your module's providers)



    @Injectable()
    export class ErrorInterceptor implements HttpInterceptor
    constructor()

    intercept(req: HttpRequest<any>, next: HttpHandler)
    return next.handle(req).pipe(
    catchError((errorResponse: HttpErrorResponse) =>
    console.error(errorResponse.error);
    )
    );





    providers: [
    provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true
    ],


    As the name implies, you can now "intercept" all incoming http responses and check for an error. Depending on what you're using to send back your response on the backside, your response after an error (this is express).



    res.status(500).json( message: "Server Boo-Boo" );


    Then you can access the message with:



    errorResponse.error.message;






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 22 at 15:54









    docb45docb45

    7117




    7117












    • The HttpInterceptor will catch every response, it's not the question here.

      – Martin Paucot
      Mar 22 at 16:01











    • It will only catch all of them if you want it to. They can easily be filtered based on response code, message or anything else.

      – docb45
      Mar 22 at 16:44











    • I already had an interceptor in place for authentication so I filtered it based on response code 500

      – Smooth
      Mar 22 at 16:54

















    • The HttpInterceptor will catch every response, it's not the question here.

      – Martin Paucot
      Mar 22 at 16:01











    • It will only catch all of them if you want it to. They can easily be filtered based on response code, message or anything else.

      – docb45
      Mar 22 at 16:44











    • I already had an interceptor in place for authentication so I filtered it based on response code 500

      – Smooth
      Mar 22 at 16:54
















    The HttpInterceptor will catch every response, it's not the question here.

    – Martin Paucot
    Mar 22 at 16:01





    The HttpInterceptor will catch every response, it's not the question here.

    – Martin Paucot
    Mar 22 at 16:01













    It will only catch all of them if you want it to. They can easily be filtered based on response code, message or anything else.

    – docb45
    Mar 22 at 16:44





    It will only catch all of them if you want it to. They can easily be filtered based on response code, message or anything else.

    – docb45
    Mar 22 at 16:44













    I already had an interceptor in place for authentication so I filtered it based on response code 500

    – Smooth
    Mar 22 at 16:54





    I already had an interceptor in place for authentication so I filtered it based on response code 500

    – Smooth
    Mar 22 at 16:54











    0














    I was able to solve the issue by using an HttpIntercepter



    import Injectable from "@angular/core";
    import
    HttpRequest,
    HttpHandler,
    HttpEvent,
    HttpInterceptor,
    HttpErrorResponse
    from "@angular/common/http";
    import Observable, of, throwError from "rxjs";
    import catchError from 'rxjs/operators';


    @Injectable()
    export class AuthInterceptor implements HttpInterceptor

    constructor(public auth: AuthService, public navService: NavService)

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
    let request = req.clone(
    withCredentials: true
    );

    return next.handle(request).pipe(catchError((err, caught) =>
    if (err instanceof HttpErrorResponse)
    if (err.status === 500)
    return throwError(err)


    return of(err);
    ) as any);







    share|improve this answer



























      0














      I was able to solve the issue by using an HttpIntercepter



      import Injectable from "@angular/core";
      import
      HttpRequest,
      HttpHandler,
      HttpEvent,
      HttpInterceptor,
      HttpErrorResponse
      from "@angular/common/http";
      import Observable, of, throwError from "rxjs";
      import catchError from 'rxjs/operators';


      @Injectable()
      export class AuthInterceptor implements HttpInterceptor

      constructor(public auth: AuthService, public navService: NavService)

      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
      let request = req.clone(
      withCredentials: true
      );

      return next.handle(request).pipe(catchError((err, caught) =>
      if (err instanceof HttpErrorResponse)
      if (err.status === 500)
      return throwError(err)


      return of(err);
      ) as any);







      share|improve this answer

























        0












        0








        0







        I was able to solve the issue by using an HttpIntercepter



        import Injectable from "@angular/core";
        import
        HttpRequest,
        HttpHandler,
        HttpEvent,
        HttpInterceptor,
        HttpErrorResponse
        from "@angular/common/http";
        import Observable, of, throwError from "rxjs";
        import catchError from 'rxjs/operators';


        @Injectable()
        export class AuthInterceptor implements HttpInterceptor

        constructor(public auth: AuthService, public navService: NavService)

        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
        let request = req.clone(
        withCredentials: true
        );

        return next.handle(request).pipe(catchError((err, caught) =>
        if (err instanceof HttpErrorResponse)
        if (err.status === 500)
        return throwError(err)


        return of(err);
        ) as any);







        share|improve this answer













        I was able to solve the issue by using an HttpIntercepter



        import Injectable from "@angular/core";
        import
        HttpRequest,
        HttpHandler,
        HttpEvent,
        HttpInterceptor,
        HttpErrorResponse
        from "@angular/common/http";
        import Observable, of, throwError from "rxjs";
        import catchError from 'rxjs/operators';


        @Injectable()
        export class AuthInterceptor implements HttpInterceptor

        constructor(public auth: AuthService, public navService: NavService)

        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
        let request = req.clone(
        withCredentials: true
        );

        return next.handle(request).pipe(catchError((err, caught) =>
        if (err instanceof HttpErrorResponse)
        if (err.status === 500)
        return throwError(err)


        return of(err);
        ) as any);








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 22 at 16:10









        SmoothSmooth

        4521929




        4521929



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55303128%2fangular-7-how-to-capture-500-server-error-on-http-post-when-returning-a-new-pr%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript