The CerebralError
class allows you to create custom error types that integrate with Cerebral’s error handling system. Custom errors can be caught specifically in the module’s catch
configuration.
Extend the CerebralError
class to create custom error types:
import { CerebralError } from 'cerebral'
export class AuthenticationError extends CerebralError {
constructor(message, details) {
super(message, details)
this.name = 'AuthenticationError' // Override the default name
}
}
// With additional properties
export class ApiError extends CerebralError {
constructor(message, statusCode, responseData) {
super(message, { responseData }) // Details passed to parent
this.name = 'ApiError'
this.statusCode = statusCode // Custom property
}
}
The CerebralError
includes these properties:
name
: Error type name, defaults to ‘CerebralError’ (should be overridden)message
: The error messagedetails
: Optional object with additional error detailsstack
: Stack trace (automatically generated)Throw custom errors in actions or providers:
import { AuthenticationError } from './errors'
function authenticate({ props }) {
if (!props.token) {
throw new AuthenticationError('Invalid token', {
attempted: true,
userId: props.userId
})
}
// Continue with authentication
}
Errors are caught in the module’s catch
configuration:
import { AuthenticationError, ApiError } from './errors'
import * as sequences from './sequences'
export default {
// ...module definition
catch: [
// Catch specific error types
[AuthenticationError, sequences.handleAuthError],
[ApiError, sequences.handleApiError],
// Generic fallback (catches any Error)
[Error, sequences.handleGenericError]
]
}
If a module doesn’t catch an error, it propagates up to parent modules until caught or reaching the root. This enables centralized error handling for common errors while allowing specialized handling in specific modules.
CerebralError
instances can be serialized to JSON, which includes all properties except ‘toJSON’, ‘execution’, and ‘functionDetails’:
try {
throw new ApiError('Failed to fetch data', 404, { error: 'Not found' })
} catch (error) {
console.log(JSON.stringify(error))
// Output includes: name, message, details, statusCode, stack
}