I’m developing a heavy AJAX Symfony 2 app. Most of my actions begin this way:
if($this->getRequest()->isXmlHttpRequest()) {
// Do something
}
The action only must be executed in case it’s responding to an AJAX request. I thought it would be better for sake of simplicity and better indentation to do things this way:
if(false === $this->getRequest()->isXmlHttpRequest()) {
// throw some exception
}
// Do something
My problem is I don’t know what’s the most appropiate Exception I could throw. I’d like to get some feedback on the subject. Maybe AccessDeniedException? Would any of Symfony predefined Exception fit? Or should I create a new Exception extending the base PHP Exception class? Any opinions will be really appreciated and sorry for my English.
Edit: What about this one?
https://github.com/symfony/HttpKernel/blob/master/Exception/BadRequestHttpException.php
You didn’t mention authentication, so I’m assuming it’s not an issue here.
That being the case, I wouldn’t use. Here’s the definition for theAccessDeniedException, since it will produce a401 Unauthorizederror, which means that the user’s credentials were incorrect or missing401 Unauthorizedstatus:I also wouldn’t go with
BadRequestHttpException. That will return a400response, which means that the server didn’t understand the request. I think in this case, the server understands the request, but is refusing to fulfill it. Here’s the full definition for a400response:I think the HTTP status that closest matches your case here is
403 Forbidden:According to Symfony on github, it doesn’t look like Symfony has a
ForbiddenException, or anything similar… Which I think is a little strange (maybe I’m missing something?).If that’s the case, you can write your own, implementing the
HttpExceptionInterface(or simply by extendingHttpException). That, or you can just create a generic one on the fly: