How to pass express errors message to Angular view ?

19 Jul, 2021
There are mainly two parts of a web application, one is front-end and another is the backend. We will start with the backend first. The express catches all errors that occur while running route handlers and middleware. We have to just send them properly to the frontend for user knowledge.
Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler, so you don’t need to write your own to get started.
Approach: 
Create the Angular app to be used.
Create the backend routes as well.
We send the error during user signup fail. So we have created the “/signup” route in the express app. Now on signup failure send the error using res.status(401).json() method.
Now on the frontend side, the auth.service.ts is sending the signup request to the backend. This will return an observable response. So we can subscribe to this request and except the backend response on the frontend side.
So either the error case or success case is handle inside the returned observable.
Example: Explain it with a very simple example let’s say we are trying to create a new user in the database and send a post request for this from the signup page. 
users.js
router.post('/signup',UserController.(req,res)=>{    bcrypt.hash(req.body.password,10)    .then((hash)=>{        var user = new User({            email: req.body.email,            password: hash        })        User.save((err,d)=>{            if(err){                res.status(401).json({                    message: 'Failed to create new user'                })            } else{                res.status(200).json({                    message: 'User created'                })            }        })    })})
In the above code, we will send a post request on /signup route than using the bcrypt library to encoding the password then create a user object that holds the data that we want to save in the database. Then User.save() method saves the data to the database then either of two scenarios occurs so either data saved successfully in a database or any error occurred. 
So, if data saved successfully then we can send the success response to the user.
Syntax:
res.status(200).json({
    message: 'User created'
})
But if data is not saved to the database then we get an error object in the callback. If we get an error, or we know the scenario in which error occurs then we simply send.
res.status(401).json({   message: 'Failed to create new user'})
It was either send an error message through res.status(200).send({ message: ‘user created’ }); with a 200 HTTP status, or send a 401 or 403 HTTP status with no further info on what actually went wrong with a res.status(401).
Handling Error on frontend side
So by this way, we can send it as a response to the frontend now on the frontend side in angular we can handle this simply in the service file, so we have created an auth.service.ts file from where we send a request to the backend.
auth.service.ts
addUser(user) {    this.http.post(BACKEND_URL + '/signup', user)        .subscribe((res) => {            this.router.navigate(['/auth/login']);        }, (err) => {            this.error = err.message;            console.log(err.message);            // In this block you get your error message            // as "Failed to create new user"        });}
Here we have created an addUser() method that sends HTTP request to the backend (Express framework) providing user details so this.http.post() method returns an Observable, so we can subscribe this and this provides us three callback methods first is success case, second is error case and the third is done (when all operations performed or end). In the success case, we are navigating the user to the login page.
auth.service.ts
}, (err) => {    console.log(err.error.message);    this.error = err.message;    // In this block you get your error message    // as "Failed to create new user"});
So in the second callback method, we can access the error message that we are sending from the backend. So we can send any data from backend to frontend.
Output:
AngularJS-Function
AngularJS-Questions
Express.js
Picked
AngularJS
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.