User Exception Behavior in symfony2

I am trying to figure out how to create custom exception behavior. When I throw an exception using

 throw new \Exception('Error occurred with your request please try again');

I automatically get status 500 and message as an internal server error

However, instead, I would like my answer to include my exception message, and not just the internal server error, so to display something like this:

 {
   "error":{
      "code":500, 
      "message":"Error occurred with your request please try again"
   }
 }

and, besides, perhaps some additional things, such as email error itself. However, I only want this to happen when I throw \ Exception and not use something like

    throw new HttpException

Any help or ideas on how to do this.

I should also mention that I do not use Twig or any templates for this. This is strictly an API type response.

+3
source
2

http://symfony.com/doc/current/cookbook/controller/error_pages.html. .

, /Resources/TwigBundle/views/Exception/exception.json.twig exception.message error_code.

:

{% spaceless %}
{
  "error":{
    "code": {{ error_code }}, 
    "message":{{ exception.message }}
  }
}
{% endspaceless %}

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);
        $event->setResponse($response);
    }
}

:

json_exception_listener:
    class: Your\Namespace\JsonExceptionListener
    tags:
        - { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 200 }

+8

, , , , 200. , - try catch:

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'));
}

json- , , .

, ,

}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
    }
}
0

All Articles