Exceptions

The Web Push library uses a hierarchy of specific exceptions to provide clear error messages and enable precise error handling.

Exception Hierarchy

WebPushException (interface)
└── AbstractWebPushException
    ├── ValidationException
    │   ├── InvalidTopicException
    │   ├── InvalidTTLException
    │   ├── InvalidUrgencyException
    │   └── InvalidPayloadException
    └── OperationException (deprecated, use specific exceptions)

Validation Exceptions

All validation exceptions extend ValidationException and expose the problematic value as a public readonly property, making debugging easier.

InvalidTopicException

Thrown when a notification topic is invalid.

Property: public readonly string $topic

Causes:

  • Empty topic

  • Topic exceeds 32 characters

  • Topic contains invalid characters (only a-z, A-Z, 0-9, -, ., _, ~ allowed)

InvalidTTLException

Thrown when a notification TTL (Time-To-Live) is invalid.

Property: public readonly int $ttl

Causes:

  • Negative TTL value

InvalidUrgencyException

Thrown when a notification urgency is invalid.

Property: public readonly string $urgency

Causes:

  • Urgency value not in: very-low, low, normal, high

InvalidPayloadException

Thrown when a notification payload is invalid.

Property: public readonly int $size

Causes:

  • Payload exceeds maximum size

Error Handling Strategies

Strategy 1: Catch Specific Exceptions

Handle each type of validation error differently:

Strategy 2: Catch All Validation Errors

Use the base ValidationException to catch any validation error:

Strategy 3: Provide User Feedback

Use exception properties to give specific feedback to users:

Strategy 4: Logging with Context

Log validation errors with full context for debugging:

Best Practices

1. Catch Specific Exceptions

Prefer catching specific exceptions over the generic ValidationException when you need different handling:

2. Use Exception Properties

Leverage the public readonly properties for debugging and logging:

3. Validate Early

Validate user input as early as possible:

4. Provide Helpful Error Messages

Transform technical exceptions into user-friendly messages:

Common Scenarios

Form Validation

API Error Responses

Testing

Migration from OperationException

If your code currently catches OperationException, you can migrate gradually:

Before (still works)

Summary

Specific Exceptions - Each validation error has its own exception type ✅ Contextual Properties - Access problematic values via public readonly properties ✅ Type-Safe - IDEs can autocomplete exception types and properties ✅ Better Debugging - Log exact values that caused errors ✅ Granular Handling - Catch and handle specific error types differently ✅ User-Friendly - Transform technical errors into helpful messages

Next Steps

Last updated

Was this helpful?