Data Processing Error Class
Build and use a DataProcessingError class, which can be thrown in scenarios where data transformation or processing fails.
class DataProcessingError extends Error {
constructor(message) {
super(message);
this.name = 'DataProcessingError';
}
}
Defines a custom error class specifically for data processing errors, extending the built-in Error class in JavaScript.
function processData(data) {
try {
// Simulate data processing that fails
if (data.isValid === false) {
throw new DataProcessingError('Invalid data encountered during processing.');
}
// More data processing logic here...
return true; // Placeholder for successful data processing
} catch (error) {
// Re-throw custom data processing errors
if (error instanceof DataProcessingError) {
throw error;
} else {
// Handle other error types (e.g., TypeError)
console.error('An unexpected error occurred:', error);
}
}
}
Implements a processData function that simulates data processing. It throws a DataProcessingError if the data is invalid. It also includes error handling that distinguishes between DataProcessingErrors and other error types.
try {
// Example invalid data object
const data = { isValid: false };
processData(data);
} catch (error) {
if (error instanceof DataProcessingError) {
console.error('Data processing failed:', error.message);
}
}
Runs the processData function with an example invalid data object and includes a try-catch block to handle the thrown DataProcessingError, outputting an error message to the console.