Blog>
Snippets

Error Handling in Angular Universal

Exhibit a way to catch and manage errors during server-side rendering, including showing custom error pages.
import { NgModule, ErrorHandler } from '@angular/core';
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';

// Custom error handler
export class UniversalErrorHandler implements ErrorHandler {
  handleError(error: any): void {
    console.error('Error occurred:', error);
    // Your custom server-side error handling goes here
  }
}

@NgModule({
  imports: [ServerModule, ServerTransferStateModule],
  providers: [{ provide: ErrorHandler, useClass: UniversalErrorHandler }]
})
export class AppServerModule {}
This code defines a custom ErrorHandler that overrides the default Angular ErrorHandler. Any errors that occur during server-side rendering will be caught by this handler, and the 'handleError' method will output the error details to the console. The custom handler is provided in the 'providers' array of the AppServerModule to ensure it is used server-side.
import { Response } from 'express';

export function handleRenderError(err: Error, res: Response): void {
  console.error('Render Error:', err);
  res.status(500).render('500', { error: err.message });
}
This function can be used in your Express server configuration to handle rendering errors. When an error occurs, it logs the error to the console and then sends a 500 status code along with rendering a custom 500 error page with the error message.
server.get('*', (req, res) => {
  res.render('index', { req }, (err, html) => {
    if (err) {
      return handleRenderError(err, res);
    }
    res.send(html);
  });
});
This snippet hooks up the error handling function to your Express server routes. For any GET request, it attempts to render 'index'. If an error occurs during rendering, the 'handleRenderError' function is called, handling the error and displaying the custom error page.