π JavaScript Intro to Error Handling
In JavaScript, errors are inevitable. Whether they come from user input, network issues, or logical errors in your code, handling them gracefully is crucial for creating robust applications. Error handling allows you to manage these situations, ensuring your program can recover or fail gracefully.
JavaScript provides built-in mechanisms for handling errors. The most common approach involves the try
, catch
, and finally
statements, which allow you to catch errors and take appropriate actions. Additionally, you can create custom error types to provide more specific error information.
Built-in Error Types
JavaScript includes several built-in error types, each representing a different kind of error:
Error
: The generic error type.SyntaxError
: Thrown when there is a syntax error in the code.ReferenceError
: Thrown when an invalid reference is used.TypeError
: Thrown when a value is not of the expected type.RangeError
: Thrown when a number is outside the allowable range.URIError
: Thrown when there is an error in encoding or decoding a URI.
Examples
// SyntaxError: Triggered by incorrect JSON syntax
try {
JSON.parse('{ invalid JSON }');
} catch (error) {
console.error(error.name + ': ' + error.message);
}
// ReferenceError: Using an undefined variable
try {
console.log(nonExistentVariable);
} catch (error) {
console.error(error.name + ': ' + error.message);
}
// TypeError: Calling a method on a null value
try {
null.f();
} catch (error) {
console.error(error.name + ': ' + error.message);
}
// RangeError: Passing an invalid length to a string method
try {
let num = 1;
num.toFixed(1000);
} catch (error) {
console.error(error.name + ': ' + error.message);
}
// URIError: Passing a malformed URI to decodeURIComponent
try {
decodeURIComponent('%');
} catch (error) {
console.error(error.name + ': ' + error.message);
}
The `Error` Object
The `Error` object in JavaScript is a built-in object that provides error information when something goes wrong. It includes several properties:
name
: The name of the error. This is usually "Error".message
: A description of the error.
Creating an Error
let error = new Error('Something went wrong');
console.log(error.name); // "Error"
console.log(error.message); // "Something went wrong"
The `throw` Statement
The `throw` statement is used to generate an error. When an error is thrown, the execution of the current function stops, and control is passed to the nearest `catch` block.
Syntax
throw expression;
Example
function riskyOperation() {
throw new Error('Something went wrong');
}
try {
riskyOperation();
} catch (error) {
console.error('An error occurred:', error.message);
}
Try/Catch/Finally
The try
, catch
, and finally
blocks allow you to handle errors in a structured way. Hereβs how they work:
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that will run regardless of whether an error occurred
}
Explanation:
try
block: Contains the code that may throw an error.catch
block: Contains the code to handle the error if one occurs. Theerror
object provides details about the error.finally
block: Contains the code that will run regardless of whether an error occurred. It is optional and can be used for cleanup tasks.
Example
try {
let result = riskyOperation();
console.log(result);
} catch (error) {
console.error('An error occurred:', error.message);
} finally {
console.log('This will run regardless of an error.');
}
function riskyOperation() {
throw new Error('Something went wrong');
}
Here's how it works:
- The
riskyOperation
function is called inside thetry
block. This function throws an error with the message "Something went wrong". - When the error is thrown, the code inside the
catch
block is executed, logging the error message to the console. - The
finally
block runs after thetry
andcatch
blocks, logging a message regardless of whether an error occurred.
Custom Errors
Sometimes, you may want to create custom error types to provide more specific error information. You can do this by creating a function that returns an error object with a custom message and name.
function CustomError(message) {
const error = new Error(message);
error.name = 'CustomError';
return error;
}
try {
throw CustomError('This is a custom error');
} catch (error) {
console.error('An error occurred:', error.message);
}
Here's how it works:
- The
CustomError
function creates a new error object with a custom message and name. - The
throw
statement is used to throw the custom error. - The
catch
block handles the custom error, logging its message to the console.
Putting It Into Action
To see these examples in action, create an HTML file and include the following script. This script will demonstrate error handling and log the results to the console.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Error Handling Example>/title>
</head>
<body>
<script>
// Try/Catch/Finally example
try {
let result = riskyOperation();
console.log(result);
} catch (error) {
console.error('An error occurred:', error.message);
} finally {
console.log('This will run regardless of an error.');
}
function riskyOperation() {
throw new Error('Something went wrong');
}
// Custom Error example
function CustomError(message) {
const error = new Error(message);
error.name = 'CustomError';
return error;
}
try {
throw CustomError('This is a custom error');
} catch (error) {
console.error('An error occurred:', error.message);
}
</script>
</body>
</html>
Challenge
Modify the error handling examples to include additional logic in the catch
blocks, such as logging the errors to a remote server or retrying the failed operations.
In order to check your learning, you should attempt to create a solution before revealing the provided solution below.
// Try/Catch/Finally example with additional logic
try {
let result = riskyOperation();
console.log(result);
} catch (error) {
console.error('An error occurred:', error.message);
// Additional logic: Log error to a remote server
logErrorToServer(error);
} finally {
console.log('This will run regardless of an error.');
}
function riskyOperation() {
throw new Error('Something went wrong');
}
function logErrorToServer(error) {
console.log('Logging error to server:', error.message);
}
// Custom Error example with retry logic
function CustomError(message) {
const error = new Error(message);
error.name = 'CustomError';
return error;
}
function retryOperation() {
try {
throw CustomError('This is a custom error');
} catch (error) {
console.error('An error occurred:', error.message);
// Retry logic
console.log('Retrying operation...');
retryOperation();
}
}
retryOperation();