I would like to ensure that, even when it screws up, the event tracking code in my front end never causes an error that impacts the rest of the application. The event tracking is all handled by a few custom classes that deal with labeling evenings and adding the correct properties:
export class TaskTrackerService {
constructor(private abstractTracker: TrackerService) { }
// ------
created(task: Task): void {
this. abstractTracker.track('Task created', this.taskProps(task))
}
// ------
edited(task: Task): void {
this.abstractTracker.track('Task edited', this.taskProps(task))
}
// ------
private taskProps(task: Task): EventProperties{
return {
id: task.id,
task_title_char_count: task.title.length,
task_duration_seconds: task.duration,
completed: task.done,
created_at: new Date(task.created_at)
}
}
}
This class contains logic which could cause errors (e.g. task.created_at is null in the code above) and I want to ensure I catch these before they cause damage.
I want to ensure that any errors that are triggered in the tracking class don't propagate anywhere else in the app.
The only way I can think to do this is to add error handling for each individual tracking method as shown below:
export class TaskTrackerService {
constructor(private abstractTracker: TrackerService) { }
// ------
created(task: Task): void {
try{
this.abstractTracker.track('Task created', this.taskProps(task))
} catch(error){
this.abstractTracker.trackError('Error occurred')
}
}
...
}
To reduce the amount of boilerplate code, I'd like some means to ensure that all of the instanc methods bubble their errors into a class-level handler. Something like this:
export class TaskTrackerService {
constructor(private abstractTracker: TrackerService) { }
// I know this isn't possible but...
catchAll(error){
this.abstractTracker.trackError('Error occurred')
}
// ------
created(task: Task): void {
this.abstractTracker.track('Task created', this.taskProps(task))
}
...
}
Is anything like this possible?