Error Handling
Effective error handling is crucial for building resilient applications. Dvori provides robust mechanisms to catch and handle errors, both at the request level using try/catch with async/await and globally through the onError
lifecycle hook. This guide demonstrates how to manage errors to maintain stability and reliability in your applications.
Catching Errors
Wrap your requests in a try/catch block to handle errors gracefully.
Example: Handling Request Errors
This approach allows you to handle errors locally, providing flexibility to manage different types of errors in context.
Global Error Handling with onError Lifecycle Hook
For a more centralized approach to error handling, use the onError
lifecycle hook. It allows you to catch and handle errors globally, applying custom logic across all requests.
Example: Global Error Logger
The onError
hook provides a centralized point to manage errors, ideal for logging, monitoring, or applying common recovery strategies.
Best Practices
- Specific Error Handling: Use try/catch for specific error handling where you anticipate failures and need custom logic to recover.
- Centralized Logging: Utilize the
onError
lifecycle hook for centralized error logging or handling that applies across all requests. - Error Propagation: Consider re-throwing errors in the
onError
hook if subsequent handling is needed or to allow for specific catch blocks to handle them.