larval 如何捕獲mysql錯誤

larval捕獲mysql錯誤的方法:1、使用errorInfo變量返回SQLSTATE錯誤和消息;2、使用異常處理程序“app/Exceptions/Handler.php并偵聽QueryExceptions”將所有SQL錯誤記錄到數(shù)據(jù)。

larval 如何捕獲mysql錯誤

推薦:《mysql視頻教程

Laravel使用PDO,因此您可以使用errorInfo變量返回SQLSTATE錯誤和消息。基本上,您需要使用$e->errorInfo;

如果要將所有SQL錯誤記錄到數(shù)據(jù)庫中,可以使用異常處理程序(app/Exceptions/Handler.php并偵聽QueryExceptions。像這樣的:

public?function?render($request,?Exception?$e) { ????switch?($e)?{ ????????case?($e?instanceof?IlluminateDatabaseQueryException): ????????????LogTracker::saveSqlError($e); ????????????break; ????????default: ????????????LogTracker::saveError($e,?$e->getCode()); ????} ????return?parent::render($request,?$e); }

然后你可以用這樣的東西:

public?function?saveSqlError($exception) { ????$sql?=?$exception->getSql(); ????$bindings?=?$exception->getBindings() ????//?Process?the?query's?SQL?and?parameters?and?create?the?exact?query ????foreach?($bindings?as?$i?=>?$binding)?{ ????????if?($binding?instanceof?DateTime)?{ ????????????$bindings[$i]?=?$binding->format(''Y-m-d?H:i:s''); ????????}?else?{ ????????????if?(is_string($binding))?{ ????????????????$bindings[$i]?=?"'$binding'"; ????????????} ????????} ????} ????$query?=?str_replace(array('%',?'?'),?array('%%',?'%s'),?$sql); ????$query?=?vsprintf($query,?$bindings); ????//?Here's?the?part?you?need ????$errorInfo?=?$exception->errorInfo; ????$data?=?[ ????????'sql'????????=>?$query, ????????'message'????=>?isset($errorInfo[2])???$errorInfo[2]?:?'', ????????'sql_state'??=>?$errorInfo[0], ????????'error_code'?=>?$errorInfo[1] ????]; ????//?Now?store?the?error?into?database,?if?you?want.. ????//?.... }

以上就是larval 如何捕獲

? 版權聲明
THE END
喜歡就支持一下吧
點贊13 分享