问题
Im trying to figure out how to make a custom exception behavior. When i throw a exception using
throw new \Exception('Error occurred with your request please try again');
I automatically get status 500 and the message as internal server error
However i would instead like my response to include my exception message instead of just internal server error so for it to display something like so:
{
"error":{
"code":500,
"message":"Error occurred with your request please try again"
}
}
and on top of that possibly do some extra things such as email myself the error. However I only want this to happen when i throw a \Exception as opposed to using something like
throw new HttpException
Any help or ideas on how to accomplish this.
I should also mention that I am not using Twig or any templates for this. This is strictly a API type response
回答1:
Take a look at http://symfony.com/doc/current/cookbook/controller/error_pages.html There is enough information to get you started.
In short, you should create app/Resources/TwigBundle/views/Exception/exception.json.twig and there you have access to the exception.message and error_code.
here's solution for you:
{% spaceless %}
{
"error":{
"code": {{ error_code }},
"message":{{ exception.message }}
}
}
{% endspaceless %}
Another solution is to use Exception Listener:
namespace Your\Namespace;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class JsonExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$data = array(
'error' => array(
'code' => $exception->getCode(),
'message' => $exception->getMessage()
)
);
$response = new JsonResponse($data, $exception->getCode());
$event->setResponse($response);
}
}
update your services config:
json_exception_listener:
class: Your\Namespace\JsonExceptionListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 200 }
cheers
回答2:
If you want to be able to read the message you are sending back, you need to return a response code that returns text with the response, like 200. So you can do something like this with a try catch
block:
try{
//.....
throw new \Exception('Error occurred with your request please try again');
}catch(\Exception $ex){
$return = array('error'=>array('code'=>500,'message'=>$ex->getMessage()));
return new Response(json_encode($return),200,array('Content-Type' => 'application/json'));
}
and on the client side, you should get a json object exactly as you outlined you want it.
even better, you can do different things depending on which exception is thrown
}catch(\Exception $ex){
$class = get_class($ex);
if($class == 'Symfony\Component\HttpKernel\Exception\HttpException'){
// create a response for HttpException
}else{
// create a response for all other Exceptions
}
}
来源:https://stackoverflow.com/questions/21787482/custom-exception-behavior-in-symfony2