3

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
  • can you show your try catch block you are using? Commented Feb 14, 2014 at 21:12

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

7 Comments

Im not using twig for this i only get a request and return a response.
You have to have a exception listener anyway. Twig does it for you. Another approach would be to create custom exception listener which will output http response with JSON content. BTW what templating engine you are using?
Im not using any templating engine this is more of a API
here's an answer on SO how you can implement your exception handler: stackoverflow.com/a/10336963/2352294
I have updated my answer with exception listener example
|
-1

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

1 Comment

Nah. Too complicated. As @sickelap suggested, create your own exception listener and then you can do whatever you want. I was looking for a cookbook example but didn't see one. But their are lots of examples out there. It's also instructive to look at HTTPKernel.php to see how request are handled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.