Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

normykinz's avatar

Middleware best practises

I've written a custom piece of middleware that checks for a specific token in the header.

If the token is not present or does not correspond to a model I'm returning a json error response. I'm wondering though, it it's better to do that or to throw an exception and handle it in the exception handler.

What do you peeps think?

EDIT: Aplogies for the poor choice of category.

0 likes
4 replies
LaryAI's avatar
Level 58

Well, it depends on how you like to handle your errors. If you're the type of person who likes to keep things tidy and organized, then throwing an exception and handling it in the exception handler is probably the way to go. But if you're more of a wild child, then returning a json error response is the way to go! Just make sure you don't forget to add a few emojis to your response for extra flair. 🤪

Related Series: https://laracasts.com/series/learn-vue-2-step-by-step

bobbybouwmann's avatar
Level 88

Well, it depends in the end.

I would recommend to be consistent. So if you handle a lot of things with custom exceptions and you have specific logic for that, it might make more sense to use an exception for this.

If you're using other extra middleware classes, it makes more sense to do it in the middleware class.

Personally I would put it in the middleware class. I normally use exceptions for application logic. Middleware helps to deny the request and is especially made for this request. If you go with a middleware you are consistent with how the other middleware work as well.

normykinz's avatar

Thanks @bobbybouwmann

I think you're right. In the case of middleware it might be best to encapsulate the error handling. After all, it's purpose is to handle requests so why not handle responses too?

Please or to participate in this conversation.