symfony2中对异常的处理,个人总结

来源:互联网 发布:麦克风扩音软件 编辑:程序博客网 时间:2024/04/30 09:24

习惯了之前的出现错误,就立即解决的方式。现在在用symfony的用法,发现原来自己一直错过了一个东西:Exception

现在讲讲symfony2中如何处理错误

1.首先自己在src/AppBundle下建立了一个Exception的文件夹,

BaseException.php的异常基类
namespace AppBundle\Exception;class BaseException extends \Exception{    /**     * 未登录错误     */    const ERROR_CODE_UNLOGIN = 1001;    /**     * 没有权限错误     */    const ERROR_CODE_NO_AUTHORITY = 1002;    /**     * 参数错误     */    const ERROR_CODE_ILLEGAL_PARAMETER = 2001;    /**     * 未知错误     */    const ERROR_CODE_UNKNOWN = 5000;    /**     * 服务器内部错误     */    const ERROR_CODE_INTERNAL = 5001;}
这里还需要对其进行赋值
NoAuthorityException.php
namespace Material\Exception;/** * 无权限异常类 * * @author zhujian <zhujian@thinkerx.com> */class NoAuthorityException extends BaseException{    function __construct($message)    {        parent::__construct($message, BaseException::ERROR_CODE_NO_AUTHORITY);    }}
UnLoginException.php
namespace Material\Exception;/** * 未登录异常类 * * @author zhujian <zhujian@thinkerx.com> */class UnLoginException extends BaseException{    function __construct($message)    {        parent::__construct($message, BaseException::ERROR_CODE_UNLOGIN);

2.建一个EventListener文件-》ExceptionListener.php
<?phpnamespace Material\EventListener;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\HttpFoundation\JsonResponse;use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;class ExceptionListener{    public function onKernelException(GetResponseForExceptionEvent $event)    {        $request = $event->getRequest();        $exceptionListener = null;        $exceptionListener = new AjaxExceptionListener();        $exceptionListener->onKernelException($event);    }}
3.建一个EventListener文件-》AjaxExceptionListener.php
<?phpnamespace Material\EventListener;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\HttpFoundation\JsonResponse;use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;class AjaxExceptionListener extends ExceptionListener{    public function onKernelException(GetResponseForExceptionEvent $event)    {        $exception = $event->getException();        $response = new JsonResponse(array(            'status' => $exception->getCode(),            'msg' => $exception->getMessage(),        ));        $event->setResponse($response);    }}
这样的话有错误,我们就可以进行抛出错误,最后在Event进行监听,处理。

1 0
原创粉丝点击