Nice programing

Laravel : DB :: transaction ()과 함께 try… catch 사용

nicepro 2020. 12. 6. 22:07
반응형

Laravel : DB :: transaction ()과 함께 try… catch 사용


우리는 모두 DB::transaction()다중 삽입 쿼리에 사용 합니다. 그 안에을 try...catch넣거나 포장해야합니까? 문제가 try...catch발생하면 트랜잭션이 자동으로 실패 할 때 를 포함해야 합니까?

try...catch트랜잭션 래핑 샘플 :

// try...catch
try {
    // Transaction
    $exception = DB::transaction(function() {

        // Do your SQL here

    });

    if(is_null($exception)) {
        return true;
    } else {
        throw new Exception;
    }

}
catch(Exception $e) {
    return false;
}

반대로 DB::transaction()try ... catch :

// Transaction
$exception = DB::transaction(function() {
    // try...catch
    try {

        // Do your SQL here

    }
    catch(Exception $e) {
        return $e;
    }

});

return is_null($exception) ? true : false;

또는 단순히 try ... catch없이 트랜잭션

// Transaction only
$exception = DB::transaction(function() {

    // Do your SQL here

});

return is_null($exception) ? true : false;

코드를 통해 트랜잭션을 수동으로 '종료'해야하는 경우 (예외를 통하거나 단순히 오류 상태를 확인하는 경우) 사용해서는 안되며 DB::transaction()대신 코드를 DB::beginTransactionDB::commit/로 래핑해야합니다 DB::rollback().

DB::beginTransaction();

try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}

트랜잭션 문서를 참조하십시오 .


PHP7을 사용하는 경우 사용자 예외 및 치명적인 오류를 포착 하기 위해 Throwable in catch사용하십시오 .

예를 들면 :

DB::beginTransaction();

try {
    DB::insert(...);    
    DB::commit();
} catch (\Throwable $e) {
    DB::rollback();
    throw $e;
}

코드가 PHP5와 호환되어야하는 경우 Exception사용하십시오 Throwable.

DB::beginTransaction();

try {
    DB::insert(...);    
    DB::commit();
} catch (\Exception $e) {
    DB::rollback();
    throw $e;
} catch (\Throwable $e) {
    DB::rollback();
    throw $e;
}

당신은 당신이 깊은 내부를 보면 ,, laravel 5 여기에, 내가 사용 내 예제 코드를 리버스도시켜 try..catch를 통해 거래를 포장 또는 수 DB:transaction()Illuminate\Database\Connection, 당신처럼 같은 수동 트랜잭션을 작성하는 것이를

라 라벨 거래

public function transaction(Closure $callback)
    {
        $this->beginTransaction();

        try {
            $result = $callback($this);

            $this->commit();
        }

        catch (Exception $e) {
            $this->rollBack();

            throw $e;
        } catch (Throwable $e) {
            $this->rollBack();

            throw $e;
        }

        return $result;
    }

이렇게 코드를 작성하고 플래시를 통해 양식에 메시지를 다시 던지거나 다른 페이지로 리디렉션하는 것과 같은 예외를 처리 할 수 ​​있습니다. REMEMBER return inside Closure는 transaction ()에 반환되므로 반환 redirect()->back()하면 즉시 리디렉션되지 않습니다. 트랜잭션을 처리하는 변수에서 반환 되었기 때문입니다.

랩 트랜잭션

$result = DB::transaction(function () use ($request, $message) {
   try{

      // execute query 1
      // execute query 2
      // ..

      return redirect(route('account.article'));

   } catch (\Exception $e) {
       return redirect()->back()
          ->withErrors(['error' => $e->getMessage());
    }
 });

// redirect the page
return $result;

then the alternative is throw boolean variable and handle redirect outside transaction function or if your need to retrieve why transaction failed you can get it from $e->getMessage() inside catch(Exception $e){...}

참고URL : https://stackoverflow.com/questions/22906844/laravel-using-try-catch-with-dbtransaction

반응형