# Multiple error handlers

**URL:** <https://discourse.slimframework.com/t/multiple-error-handlers/5079>\
**Category:** Questions\
**Created:** [January 17, 2022, 9:14pm UTC](https://discourse.slimframework.com/t/multiple-error-handlers/5079 "2022-01-17T21:14:10Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![d12f](https://avatars.discourse-cdn.com/v4/letter/d/57b2e6/32.png) [@d12f](https://discourse.slimframework.com/u/d12f)\
**Post date:** [January 17, 2022, 9:14pm UTC](https://discourse.slimframework.com/t/multiple-error-handlers/5079/1 "2022-01-17T21:14:10Z")

</div>

Good day! I apologize if the topic duplicates a question. Tell me, please, is it possible to make a handler for one router using Twig, and the next one using JSON. Here is my first router:

```auto
// ....
if (1 < 0) {
     throw new Exception('This message must be passed to the template or json for ajax and stop the further work of the script');
}
// ....

```

---

<div class="post-metadata">

**Author:** ![odan](https://avatars.discourse-cdn.com/v4/letter/o/9de053/32.png) [@odan](https://discourse.slimframework.com/u/odan)\
**Post date:** [January 18, 2022, 8:13am UTC](https://discourse.slimframework.com/t/multiple-error-handlers/5079/2 "2022-01-18T08:13:31Z")

</div>

Could you please add more details to your question?

Generally, Twig is a template engine and JSON a special format for structured data.  
Do you mean: How to return HTML or JSON in a handler?

---

<div class="post-metadata">

**Author:** ![d12f](https://avatars.discourse-cdn.com/v4/letter/d/57b2e6/32.png) [@d12f](https://discourse.slimframework.com/u/d12f)\
**Post date:** [January 26, 2022, 4:27pm UTC](https://discourse.slimframework.com/t/multiple-error-handlers/5079/3 "2022-01-26T16:27:40Z")

</div>

i mean return exception depending on router

---

<div class="post-metadata">

**Author:** ![odan](https://avatars.discourse-cdn.com/v4/letter/o/9de053/32.png) [@odan](https://discourse.slimframework.com/u/odan)\
**Post date:** [January 26, 2022, 5:17pm UTC](https://discourse.slimframework.com/t/multiple-error-handlers/5079/4 "2022-01-26T17:17:35Z")

</div>

Yes, this is possible.

The Slim ErrorMiddlware is doing something similar, depending on the request `Accept` header.

But you wrote, you want to define the response depending on the route.  
So you could implement one Middleware for each mime type that catches all Exceptions and transforms the Exception into a proper response (HTML or JSON). For example a `JsonExceptionMiddleware` and a `HtmlExceptionMiddleware`. Then add this middleware to the routes or route groups you need.
