0

In my Node.js app I return an error like this:

app.get('/api/login', (req, res, next) => {
    //...
    return res.status(400).send({
        isSuccess: false,
        errors: ["error 1", "error 2"]
    })
})

In Angular, how can I get the error?

login() {
    const headers = new HttpHeaders().set('Accept', 'application/json').set('Content-Type', 'application/json');
    this.http.post('http://localhost:3000/api/login', { username: 'arwels', password: '24899632' }, { headers: headers }).subscribe(response => {
        // ok 
      }, (err) => {
        console.log(err) // Bad Reqeust
      });
}

When I print err in the error section, it prints Bad Reqeust. Where is the object that is sent by the server?

1
  • 1
    Its should be in your response. You will need to check the response code and based on the code render the desired error. err would only arise on a request or syntax failure. Commented Feb 2, 2020 at 22:25

1 Answer 1

1

You can use an HttpInterceptor to capture error responses from your API.

Ref: https://angular.io/api/common/http/HttpInterceptor

Here's an Example:

export class MyHttpInterceptor implements HttpInterceptor {
    constructor() {
    }
    intercept( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            catchError(async (_err: HttpErrorResponse, _caught: any) => {
                switch (_err.status) {
                    case 401:
                    ...
                        break;
                    case 500:
                    ...
                        break;
                    default:
                    ...
                        break;
                }
                return of(_err);
            })
        ) as any;
    }
}

Since you have full control over how you are returning your errors in your API, you can tailor the HttpInterceptor to work with any error object you want to create on your backend.

Unfavorable Option

If you just want the entire response so you can sniff out the statusCode, you can also just {observe: 'response'} in the HttpHeaders.

this.http.get<HttpResponse<any>>(<url>, {observe: 'response'}).pipe(
    tap(resp => console.log('response', resp))
);
Sign up to request clarification or add additional context in comments.

Comments

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.