This content originally appeared on DEV Community and was authored by {Tony}đź’»
Error
An error in software development is an undesired or unexpected event that occurs during the execution of a program or application. In software development, an error is every developer's nightmare and one of the reasons why people give up on software development.
Error Types
They are various types of errors associated with software development but the most dominant type of errors are
Operational Error
Functional Error
Operational Error
Operational Error in software development refers to runtime errors an application or a program encounters due to unhandled exception or another code issue. These errors can be challenging to diagonise as memory leaks, infinite loops, incorrect system configuration or a combination of these issues can be a cause of operational errors.
Functional Error
Functional error refers to bugs in the application code that prevents the program or application from performing as expected. these types of error usually require more effort to identify than operational error. The major causative of Functional error are incorrect logic, misused use cases, incorrect syntax, typos and misconfiguration.
Error Handling
Error handling is the process of identifying, responding and recovering from errors that occurs during the execution of a program or application. The way a developer handles an application error says a lot about the developer. A good developer must be a good error handler.
Error Handling Techniques
Error Handling techniques are those approach a developer uses in handling errors. the technique used in handling various errors depends greatly on the type of programming you are writing and the use case. The error technique for a security application might not be the same for an e-commerce website. they are various error handling techniques and they include
- Try, Catch and Finally Block
- The Call-back Function
- Promises
- Async and Await
- Event Emitters.
Try, Catch and Finally Block
.
the Try
, Catch
and Finally
block is a programming construct used for error handling. This construct are divided into the three blocks.
Try block: the try
block is used to enclose an code which might throw an error during execution. The purpose of this is to try
the code and catch any error that might be in the code. When a try
block is executed, the JavaScript runtime attempts to execute each statement inside the block in order. If an error occurs during the execution of any statement, control is immediately transferred to the nearest catch
block that can handle the type of error that occurred. If no matching catch
block is found, the error is thrown out of the try
block and caught by any enclosing catch
block, or the program crashes if no enclosing catch
block is found.
Catch Block: The catch
block is the next block of code after the the try
block, the catch
block is used to handle errors that might have be thrown by the try
block. The catch
block takes an error as as a parameter which contain the information about the error thrown by the try
block and inside the catch
block, developers can write code that handles the error in a controlled and predictable way, such as logging an error message, displaying a user-friendly error message, or attempting to recover from the error.
Finally Block: The finally
block is an optional block after the catch
block, this block of code are used to implement functions that will be executed regardless of whether an error is thrown or not. The main purpose of the finally
block is to perform any necessary cleanup tasks, such as releasing resources like file handles or network connections, that were acquired in the try
block. This ensures that resources are properly released even if an error occurs.
try {
client = await MongoClient.connect(uri);
// Insert the name into the collection
const result = await collection.create();
console.log('Name added to the database:', result.ops[0].name);
} catch (err) {
console.log('An error occurred while adding the name to the database:', err);
} finally {
// Close the database connection
client.close();
}
});
This code is an example of using a try-catch-finally block in Node.js to add a name to a MongoDB database.
The try
block contains the code that attempts to insert a new document into the names collection using the create
method. The await
keyword is used to make the create
method return a promise, which allows us to use the async/await
syntax for handling asynchronous operations in a synchronous style.
If an error occurs during the execution of the try
block, the error object is caught by the catch
block, which logs an error message to the console.
The finally block is used to close the MongoDB connection using the close method of the MongoClient
instance. This ensures that the database connection is always closed, regardless of whether the operation was successful or not.
By using a finally
block to close the database connection, we ensure that our application is properly cleaning up after itself and releasing any resources that were allocated during the operation. This is important to prevent resource leaks and ensure that our application is efficient and reliable.
Async and Await
in JavaScript, async
and await
keywords are used for handling asynchronous operation. the async
keyword is used to define an asynchronous function which returns a promise. the await
keyword can then be used in the function to wait for the completion of the asynchronous function before moving on to the next line of code. if an error occurs during the execution of the await
statement, it will throw an error and control will be passed to the nearest catch
block.
async function addNameToDatabase(collection, nameToAdd) {
let client;
try {
// Connect to the database
client = await MongoClient.connect(uri);
// Insert the name into the collection
const result = await collection.insertOne(nameToAdd);
console.log('Name added to the database:', result.ops[0].name);
} catch (err) {
console.error('An error occurred while adding the name to the database:', err);
} finally {
// Close the database connection
if (client) {
client.close();
}
}
}
In this code, we've defined an async function called addNameToDatabase
that takes two arguments: a collection object and a nameToAdd
string. Inside the function, we've declared a variable called client to store our database connection.
The try block contains the code that inserts the nameToAdd
string into the collection object. We're using the await keyword to wait for the insertOne
method to complete before moving on to the next line of code. If the insertOne
method throws an error, the catch block will catch it and log an error message to the console.
Finally, we have a finally
block that closes the database connection. We're using an if statement to check whether the client object exists before calling the close method, in case an error occurred before the connection was established.
To use this function, you can simply call it with your collection and nameToAdd
arguments:
const collection = db.collection('names');
const nameToAdd = 'John';
addNameToDatabase(collection, nameToAdd);
In summary, we've converted the original code into an async function that makes use of the await keyword to handle asynchronous code, and added error handling and a finally block to ensure that the database connection is closed properly.
Promises
In error handling, promises are often used to handle errors that occur during asynchronous operations such as network requests or database queries. When a promise is resolved successfully, its then()
method is called, and the result of the operation is passed to the next part of the program. If an error occurs during the operation, the promise is rejected, and the error is passed to the promise's catch()
method, which can be used to handle the error and prevent the program from crashing.
function addNameToDatabase(collection, nameToAdd) {
return MongoClient.connect(uri)
.then((client) => {
// Insert the name into the collection
return collection.insertOne(nameToAdd)
.then((result) => {
console.log('Name added to the database:', result);
// Close the database connection
client.close();
})
.catch((err) => {
console.log('An error occurred while adding the name to the database:', err);
// Close the database connection
client.close();
throw err;
});
})
.catch((err) => {
console.log('An error occurred while connecting to the database:', err);
throw err;
});
}
Here's an example of how to use promises to handle the error in the addNameToDatabase
function
In this version of the function, we're returning a promise from addNameToDatabase
, which resolves when the name is successfully added to the database, and rejects if any errors occur. We're also using promises to handle the connection to the database and the closing of the database connection.
Inside the then block that's called when MongoClient.connect(uri)
resolves, we're returning another promise that resolves when the name is successfully added to the database, and rejects if any errors occur. We're also using a catch block to handle any errors that occur during the insertion of the name, and to make sure that the database connection is closed before the error is re-thrown.
Finally, we're using another catch
block outside the then
block to handle any errors that occur during the connection to the database, and to make sure that the error is re-thrown so that it can be handled by any code that's calling addNameToDatabase.
Good Error Handling Practices
- Identifying potential source of errors.
- Anticipating possible errors and taking steps to prevent them.
- Providing clear and informative error messages that helps users and developers understand what went wrong and how to fix it.
This content originally appeared on DEV Community and was authored by {Tony}đź’»
{Tony}đź’» | Sciencx (2023-05-04T13:35:08+00:00) Error, Error Handling and Error Handling Technique. Retrieved from https://www.scien.cx/2023/05/04/error-error-handling-and-error-handling-technique/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.