Implement strategic error handling by properly checking exception types and using try/catch blocks to distinguish between user errors and system errors. Avoid runtime errors from improper type checking and categorize exceptions based on their source and required response.
Key principles:
in
to avoid runtime errors on primitive valuesExample:
// Bad - can cause runtime error on primitive exceptions
const isBadRequestExceptionFromValidationPipe =
exception instanceof Object &&
'response' in exception && // This fails on primitive values
'message' in (exception as any).response;
// Good - proper type checking
const isBadRequestExceptionFromValidationPipe =
exception instanceof Object &&
typeof exception === 'object' &&
exception !== null &&
'response' in exception;
// Strategic try/catch - separate system errors from user errors
try {
// Critical system operations that indicate internal failures
scheduledJob = await this.createScheduledUnsnoozeJob(notification, delayAmount);
snoozedNotification = await this.markNotificationAsSnoozed(command);
await this.queueJob(scheduledJob, delayAmount);
} catch (error) {
// Transform to InternalServerErrorException - needs immediate attention
throw new InternalServerErrorException('System error during snooze operation');
}
// User validation errors outside try/catch bubble up as-is
This approach prevents runtime errors from improper exception handling while ensuring system errors are properly categorized and logged for investigation.
Enter the URL of a public GitHub repository