1. 程式人生 > >Laravel 5.4 邏輯異常處理

Laravel 5.4 邏輯異常處理

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