How to pass express errors message to Angular view ?
Last Updated :
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.
javascript
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:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read