Considering your use case, you should handle error processing at the apache level.
What does it mean?
AEM returns standard error page (consider it as a very lightweight error page response). Idea is to keep error processing very light weight on AEM.
How should error handle work?
Create an error page in AEM like other pages of your site.
/content/path/to/your/site/home/errors/404.html
/content/path/to/your/site/home/errors/500.html
Error response should be handed at the apache level. In your virtual host configuration, add a Document with the path of AEM page.
ErrorDocument 404 /content/path/to/your/site/home/errors/404.html
ErrorDocument 401 /content/path/to/your/site/home/errors/500.html
How error processing will work?
- When a user hit a random URL, the request will bypass all caching layers (CDN, Dispatcher) and will hit Publisher.
- Publisher will use standard error handler and return 404 response to apache.
- Apache will use ErrorDocument configuration and PassThrough configured error page path to Dispatcher
/content/path/to/your/site/home/errors/404.html
- The dispatcher will process the error page path (either from cache or from the publisher)
- The dispatcher will return the Formatted brand/site-specific error page to end-user
How this approach will help?
- Publisher will just do sling resolution of the requested page, and return a very lightweight response. This will reduce the processing load on the publisher.
- The dispatcher will cache the formatted error page, which will further reduce the load on the publisher.
- You can configure multiple error pages, one for each virtual host, or path based for same virtual host.