How to get body/content of request from the HttpErrorResponse? [Angular ErrorHandler]
Let's say I sent a post request to the server to create a user. If the server responds with an error (for some reason), I want to get the body(form) I submitted(attached with that request) from the ErrorHandler. The reason for this is that, for example, when the "create user" fails, I want to show a notification with some details taken from the form and a button to redirect you back to the respective page with the fields populated again with the retrieved form.
This is how my ErrorHandler looks like:
@Injectable()
export class ErrorsHandler implements ErrorHandler
constructor(
private injector: Injector,
)
handleError(error: Error
angular error-handling angular-errorhandler
add a comment |
Let's say I sent a post request to the server to create a user. If the server responds with an error (for some reason), I want to get the body(form) I submitted(attached with that request) from the ErrorHandler. The reason for this is that, for example, when the "create user" fails, I want to show a notification with some details taken from the form and a button to redirect you back to the respective page with the fields populated again with the retrieved form.
This is how my ErrorHandler looks like:
@Injectable()
export class ErrorsHandler implements ErrorHandler
constructor(
private injector: Injector,
)
handleError(error: Error
angular error-handling angular-errorhandler
add a comment |
Let's say I sent a post request to the server to create a user. If the server responds with an error (for some reason), I want to get the body(form) I submitted(attached with that request) from the ErrorHandler. The reason for this is that, for example, when the "create user" fails, I want to show a notification with some details taken from the form and a button to redirect you back to the respective page with the fields populated again with the retrieved form.
This is how my ErrorHandler looks like:
@Injectable()
export class ErrorsHandler implements ErrorHandler
constructor(
private injector: Injector,
)
handleError(error: Error
angular error-handling angular-errorhandler
Let's say I sent a post request to the server to create a user. If the server responds with an error (for some reason), I want to get the body(form) I submitted(attached with that request) from the ErrorHandler. The reason for this is that, for example, when the "create user" fails, I want to show a notification with some details taken from the form and a button to redirect you back to the respective page with the fields populated again with the retrieved form.
This is how my ErrorHandler looks like:
@Injectable()
export class ErrorsHandler implements ErrorHandler
constructor(
private injector: Injector,
)
handleError(error: Error
angular error-handling angular-errorhandler
angular error-handling angular-errorhandler
asked Nov 14 '18 at 2:19
Cold CerberusCold Cerberus
234112
234112
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
First of all, you must confirm BE return JSON error in body.
Next step you can custom HttpInterceptor for your idea, more details you can search by keyword angular httpinterceptor.
It is my source for HttpInterceptor, there may be some help.
import Injectable from '@angular/core';
import HttpRequest, HttpInterceptor, HttpHandler, HttpEvent, HttpResponse from '@angular/common/http';
import Observable, throwError from 'rxjs';
import tap, catchError from 'rxjs/operators';
@Injectable()
export class SiteHttpInterceptor implements HttpInterceptor
constructor(
)
intercept(request: HttpRequest<any>, httpHandler: HttpHandler): Observable<any>
let token = localStorage.getItem('token');
if (('/api/users/token').indexOf(request.url) < 0 && token)
request = request.clone(
setHeaders:
'authorization': 'bearer ' + token,
'Authenticationtoken': 'bearer ' + token
);
return httpHandler.handle(request).pipe(
tap((event: HttpEvent<any>) =>
//success
,
(err: any) =>
//error
),
catchError(err =>
if (err.status === 401)
// if you want to do sth. when 401 can code here
else
// other
return throwError(err);
)
);
and please setup the HttpInterceptor to app.module.ts
import SiteHttpInterceptor from './providers/http-interceptor';
@NgModule({
providers: [ provide: RouteReuseStrategy, useClass: IonicRouteStrategy ]
Let me know is it ok for you or not :)
add a comment |
I think it's not posible to get the body from a HttpErrorResponse instance since it extends HttpResponseBase which doesn't have a body property as the normal HttpResponse does.
export declare class HttpErrorResponse extends HttpResponseBase implements Error
readonly name: string;
readonly message: string;
readonly error: any
What I've done is to use a Response Incerceptor:
import Injectable from '@angular/core';
import HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse from '@angular/common/http';
import Observable from 'rxjs/Observable';
import ResponseBusiness from '../Models/General/ResponseBusiness.model';
import MsgService from '../services/msg.service';
import AlertService from '../services/alert.service';
@Injectable()
export class ResponseInterceptor implements HttpInterceptor
constructor(private _msg: MsgService, private _alertService: AlertService)
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
return next.handle(req).map(resp =>
const response = <HttpResponse<ResponseBusiness<Object>>> resp;
if (resp instanceof HttpResponse)
/* do whatever you need with the req.body */
if (resp instanceof HttpErrorResponse)
const body = JSON.parse(req.body);
if (body && body.avoidMsg)
return resp;
if (response.status === 200 && !response.body.result.status)
this._msg.setMsg(message: `$response.body.result.codeNumber $response.body.result.codeDescription`, tipo: 'error');
return resp;
);
Then add the inteceptor to you app.module like so:
providers: [
provide: HTTP_INTERCEPTORS, useClass: ResponseInterceptor, multi: true],
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53292267%2fhow-to-get-body-content-of-request-from-the-httperrorresponse-angular-errorhan%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
First of all, you must confirm BE return JSON error in body.
Next step you can custom HttpInterceptor for your idea, more details you can search by keyword angular httpinterceptor.
It is my source for HttpInterceptor, there may be some help.
import Injectable from '@angular/core';
import HttpRequest, HttpInterceptor, HttpHandler, HttpEvent, HttpResponse from '@angular/common/http';
import Observable, throwError from 'rxjs';
import tap, catchError from 'rxjs/operators';
@Injectable()
export class SiteHttpInterceptor implements HttpInterceptor
constructor(
)
intercept(request: HttpRequest<any>, httpHandler: HttpHandler): Observable<any>
let token = localStorage.getItem('token');
if (('/api/users/token').indexOf(request.url) < 0 && token)
request = request.clone(
setHeaders:
'authorization': 'bearer ' + token,
'Authenticationtoken': 'bearer ' + token
);
return httpHandler.handle(request).pipe(
tap((event: HttpEvent<any>) =>
//success
,
(err: any) =>
//error
),
catchError(err =>
if (err.status === 401)
// if you want to do sth. when 401 can code here
else
// other
return throwError(err);
)
);
and please setup the HttpInterceptor to app.module.ts
import SiteHttpInterceptor from './providers/http-interceptor';
@NgModule({
providers: [ provide: RouteReuseStrategy, useClass: IonicRouteStrategy ]
Let me know is it ok for you or not :)
add a comment |
First of all, you must confirm BE return JSON error in body.
Next step you can custom HttpInterceptor for your idea, more details you can search by keyword angular httpinterceptor.
It is my source for HttpInterceptor, there may be some help.
import Injectable from '@angular/core';
import HttpRequest, HttpInterceptor, HttpHandler, HttpEvent, HttpResponse from '@angular/common/http';
import Observable, throwError from 'rxjs';
import tap, catchError from 'rxjs/operators';
@Injectable()
export class SiteHttpInterceptor implements HttpInterceptor
constructor(
)
intercept(request: HttpRequest<any>, httpHandler: HttpHandler): Observable<any>
let token = localStorage.getItem('token');
if (('/api/users/token').indexOf(request.url) < 0 && token)
request = request.clone(
setHeaders:
'authorization': 'bearer ' + token,
'Authenticationtoken': 'bearer ' + token
);
return httpHandler.handle(request).pipe(
tap((event: HttpEvent<any>) =>
//success
,
(err: any) =>
//error
),
catchError(err =>
if (err.status === 401)
// if you want to do sth. when 401 can code here
else
// other
return throwError(err);
)
);
and please setup the HttpInterceptor to app.module.ts
import SiteHttpInterceptor from './providers/http-interceptor';
@NgModule({
providers: [ provide: RouteReuseStrategy, useClass: IonicRouteStrategy ]
Let me know is it ok for you or not :)
add a comment |
First of all, you must confirm BE return JSON error in body.
Next step you can custom HttpInterceptor for your idea, more details you can search by keyword angular httpinterceptor.
It is my source for HttpInterceptor, there may be some help.
import Injectable from '@angular/core';
import HttpRequest, HttpInterceptor, HttpHandler, HttpEvent, HttpResponse from '@angular/common/http';
import Observable, throwError from 'rxjs';
import tap, catchError from 'rxjs/operators';
@Injectable()
export class SiteHttpInterceptor implements HttpInterceptor
constructor(
)
intercept(request: HttpRequest<any>, httpHandler: HttpHandler): Observable<any>
let token = localStorage.getItem('token');
if (('/api/users/token').indexOf(request.url) < 0 && token)
request = request.clone(
setHeaders:
'authorization': 'bearer ' + token,
'Authenticationtoken': 'bearer ' + token
);
return httpHandler.handle(request).pipe(
tap((event: HttpEvent<any>) =>
//success
,
(err: any) =>
//error
),
catchError(err =>
if (err.status === 401)
// if you want to do sth. when 401 can code here
else
// other
return throwError(err);
)
);
and please setup the HttpInterceptor to app.module.ts
import SiteHttpInterceptor from './providers/http-interceptor';
@NgModule({
providers: [ provide: RouteReuseStrategy, useClass: IonicRouteStrategy ]
Let me know is it ok for you or not :)
First of all, you must confirm BE return JSON error in body.
Next step you can custom HttpInterceptor for your idea, more details you can search by keyword angular httpinterceptor.
It is my source for HttpInterceptor, there may be some help.
import Injectable from '@angular/core';
import HttpRequest, HttpInterceptor, HttpHandler, HttpEvent, HttpResponse from '@angular/common/http';
import Observable, throwError from 'rxjs';
import tap, catchError from 'rxjs/operators';
@Injectable()
export class SiteHttpInterceptor implements HttpInterceptor
constructor(
)
intercept(request: HttpRequest<any>, httpHandler: HttpHandler): Observable<any>
let token = localStorage.getItem('token');
if (('/api/users/token').indexOf(request.url) < 0 && token)
request = request.clone(
setHeaders:
'authorization': 'bearer ' + token,
'Authenticationtoken': 'bearer ' + token
);
return httpHandler.handle(request).pipe(
tap((event: HttpEvent<any>) =>
//success
,
(err: any) =>
//error
),
catchError(err =>
if (err.status === 401)
// if you want to do sth. when 401 can code here
else
// other
return throwError(err);
)
);
and please setup the HttpInterceptor to app.module.ts
import SiteHttpInterceptor from './providers/http-interceptor';
@NgModule({
providers: [ provide: RouteReuseStrategy, useClass: IonicRouteStrategy ]
Let me know is it ok for you or not :)
answered Nov 14 '18 at 2:56
Nick WangNick Wang
44925
44925
add a comment |
add a comment |
I think it's not posible to get the body from a HttpErrorResponse instance since it extends HttpResponseBase which doesn't have a body property as the normal HttpResponse does.
export declare class HttpErrorResponse extends HttpResponseBase implements Error
readonly name: string;
readonly message: string;
readonly error: any
What I've done is to use a Response Incerceptor:
import Injectable from '@angular/core';
import HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse from '@angular/common/http';
import Observable from 'rxjs/Observable';
import ResponseBusiness from '../Models/General/ResponseBusiness.model';
import MsgService from '../services/msg.service';
import AlertService from '../services/alert.service';
@Injectable()
export class ResponseInterceptor implements HttpInterceptor
constructor(private _msg: MsgService, private _alertService: AlertService)
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
return next.handle(req).map(resp =>
const response = <HttpResponse<ResponseBusiness<Object>>> resp;
if (resp instanceof HttpResponse)
/* do whatever you need with the req.body */
if (resp instanceof HttpErrorResponse)
const body = JSON.parse(req.body);
if (body && body.avoidMsg)
return resp;
if (response.status === 200 && !response.body.result.status)
this._msg.setMsg(message: `$response.body.result.codeNumber $response.body.result.codeDescription`, tipo: 'error');
return resp;
);
Then add the inteceptor to you app.module like so:
providers: [
provide: HTTP_INTERCEPTORS, useClass: ResponseInterceptor, multi: true],
add a comment |
I think it's not posible to get the body from a HttpErrorResponse instance since it extends HttpResponseBase which doesn't have a body property as the normal HttpResponse does.
export declare class HttpErrorResponse extends HttpResponseBase implements Error
readonly name: string;
readonly message: string;
readonly error: any
What I've done is to use a Response Incerceptor:
import Injectable from '@angular/core';
import HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse from '@angular/common/http';
import Observable from 'rxjs/Observable';
import ResponseBusiness from '../Models/General/ResponseBusiness.model';
import MsgService from '../services/msg.service';
import AlertService from '../services/alert.service';
@Injectable()
export class ResponseInterceptor implements HttpInterceptor
constructor(private _msg: MsgService, private _alertService: AlertService)
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
return next.handle(req).map(resp =>
const response = <HttpResponse<ResponseBusiness<Object>>> resp;
if (resp instanceof HttpResponse)
/* do whatever you need with the req.body */
if (resp instanceof HttpErrorResponse)
const body = JSON.parse(req.body);
if (body && body.avoidMsg)
return resp;
if (response.status === 200 && !response.body.result.status)
this._msg.setMsg(message: `$response.body.result.codeNumber $response.body.result.codeDescription`, tipo: 'error');
return resp;
);
Then add the inteceptor to you app.module like so:
providers: [
provide: HTTP_INTERCEPTORS, useClass: ResponseInterceptor, multi: true],
add a comment |
I think it's not posible to get the body from a HttpErrorResponse instance since it extends HttpResponseBase which doesn't have a body property as the normal HttpResponse does.
export declare class HttpErrorResponse extends HttpResponseBase implements Error
readonly name: string;
readonly message: string;
readonly error: any
What I've done is to use a Response Incerceptor:
import Injectable from '@angular/core';
import HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse from '@angular/common/http';
import Observable from 'rxjs/Observable';
import ResponseBusiness from '../Models/General/ResponseBusiness.model';
import MsgService from '../services/msg.service';
import AlertService from '../services/alert.service';
@Injectable()
export class ResponseInterceptor implements HttpInterceptor
constructor(private _msg: MsgService, private _alertService: AlertService)
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
return next.handle(req).map(resp =>
const response = <HttpResponse<ResponseBusiness<Object>>> resp;
if (resp instanceof HttpResponse)
/* do whatever you need with the req.body */
if (resp instanceof HttpErrorResponse)
const body = JSON.parse(req.body);
if (body && body.avoidMsg)
return resp;
if (response.status === 200 && !response.body.result.status)
this._msg.setMsg(message: `$response.body.result.codeNumber $response.body.result.codeDescription`, tipo: 'error');
return resp;
);
Then add the inteceptor to you app.module like so:
providers: [
provide: HTTP_INTERCEPTORS, useClass: ResponseInterceptor, multi: true],
I think it's not posible to get the body from a HttpErrorResponse instance since it extends HttpResponseBase which doesn't have a body property as the normal HttpResponse does.
export declare class HttpErrorResponse extends HttpResponseBase implements Error
readonly name: string;
readonly message: string;
readonly error: any
What I've done is to use a Response Incerceptor:
import Injectable from '@angular/core';
import HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse from '@angular/common/http';
import Observable from 'rxjs/Observable';
import ResponseBusiness from '../Models/General/ResponseBusiness.model';
import MsgService from '../services/msg.service';
import AlertService from '../services/alert.service';
@Injectable()
export class ResponseInterceptor implements HttpInterceptor
constructor(private _msg: MsgService, private _alertService: AlertService)
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
return next.handle(req).map(resp =>
const response = <HttpResponse<ResponseBusiness<Object>>> resp;
if (resp instanceof HttpResponse)
/* do whatever you need with the req.body */
if (resp instanceof HttpErrorResponse)
const body = JSON.parse(req.body);
if (body && body.avoidMsg)
return resp;
if (response.status === 200 && !response.body.result.status)
this._msg.setMsg(message: `$response.body.result.codeNumber $response.body.result.codeDescription`, tipo: 'error');
return resp;
);
Then add the inteceptor to you app.module like so:
providers: [
provide: HTTP_INTERCEPTORS, useClass: ResponseInterceptor, multi: true],
answered Nov 14 '18 at 2:58
Gabriel LopezGabriel Lopez
2526
2526
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53292267%2fhow-to-get-body-content-of-request-from-the-httperrorresponse-angular-errorhan%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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