ErrorHandler vs ExceptionMiddleware

Hey, I was wondering whats the best practice to handle validation- and other custom exceptions.

What i got:
I have an action which calls two services:

  1. CalculationRequestValidator
  2. Calculator

The first one throws a ValidationException if validation fails, the second throws an CalculationException if something went wrong within the calculation.

What must be done on exception:
On ValidationException I pass the old fields and the error messages into session. Afterwards I respond with a redirect to the previous page.
On CalculationException I need to log the exception together with the calculation params, add a flash message to the session and respond with a redirect to the previous page.

Whats the best approach to handle these exceptions? Adding a Middleware right behind my action or adding two custom error handler to the slim ErrorMiddleware class?

Is there any rule when to use CustomErrorHandler and when to use e.g. ValidationExceptionMiddleware

Thanks! :slight_smile:

Hi @mrcde There is no “rule”, but there are different approaches. What works for you depends on the structure of your application.

You can handle these exceptions using a custom error handler in the Slim ErrorMiddleware class to perform the necessary operations.

Using a custom middleware to handle exceptions is also a viable option.

The advantage of using a middleware over a custom error handler is that the middleware can be attached to specific routes and route groups, whereas a custom error handler would be across all routes.

1 Like