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.
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. 🤪
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.
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?