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

习惯了之前的出现错误,就立即解决的方式。现在在用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 <[email protected]>
 */
class NoAuthorityException extends BaseException
{
    function __construct($message)
    {
        parent::__construct($message, BaseException::ERROR_CODE_NO_AUTHORITY);
    }
}
UnLoginException.php
namespace Material\Exception;

/**
 * 未登录异常类
 *
 * @author zhujian <[email protected]>
 */
class UnLoginException extends BaseException
{
    function __construct($message)
    {
        parent::__construct($message, BaseException::ERROR_CODE_UNLOGIN);

2.建一个EventListener文件-》 ExceptionListener.php

namespace 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

namespace 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进行监听,处理。

你可能感兴趣的:(symfony学习)