Laravel 5.4 逻辑异常处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Webben/article/details/78921755

Laravel 5.4 逻辑异常处理

修改 app\Exceptions\Handler.php

public function render($request, Exception $exception)
{
        if ($exception instanceof ValidationException) {
            return $this->invalidJson($request,$exception);
        }

        /**
         * 如果对应异常拥有渲染方法则调用
         */
        if( method_exists( $exception ,'render' )  )
        {
            return $exception->render( $request );
        }
        return parent::render($request, $exception);
    }

增加逻辑异常app\Exceptions\OrderException.php

<?php
namespace App\Exceptions;
use Exception;

class OrderException extends Exception
{
    protected $errors = [
        10011   => '订单状态错误' ,
        10012   => '订单不存在' ,
        10013   => '禁止修改订单价格' ,
    ];

    /**
     * @param $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function render( $request )
    {
        return response()->json([
            'code'      => $this->getCode() ,
            'message'   => $this->getMessage() ,
            'request_id'    => REQUEST_ID
        ] , 200 );
    }
}

异常触发

$order = Order::find( $order_id );
if( !$order )
{
    throw new OrderException(  '订单不存在' , 10012 );
}

如果需要捕捉异常的话:

try
{
    # 事务开始

    throw new Exception( '系统繁忙' );

    # 事务提交
}
catch ( Exception $e )
{
    # 事务回滚
    throw new OrderException( '订单状态修改失败' , 10011 );
}

猜你喜欢

转载自blog.csdn.net/Webben/article/details/78921755