创建时的Laravel模型错误处理


Laravel Model Error Handling when Creating

我想使用Eloquent创建一个DB条目,如下所示:

   MFUser::create(array(
        'user_reference' => $this->userReference,
        'first_name' => $this->firstName,
        'last_name' => $this->lastName,
        'user_type_id' => $this->userTypeId,
        'email' => $this->email,
        'password' => $this->password
    ));

它工作得很好,除了在字段中放入完全相同的数据时(这是意料之中的),因为不应该有重复。然后我得到QueryExection。

但是,我如何在这里正确地执行错误处理,以检查是否发生了此查询异常,从而可以通过json从服务器向客户端返回响应?

只需将代码封装在try-catch块中。类似这样的东西:

try {
    MFUser::create(array(
        'user_reference' => $this->userReference,
        'first_name' => $this->firstName,
        'last_name' => $this->lastName,
        'user_type_id' => $this->userTypeId,
        'email' => $this->email,
        'password' => $this->password
    ));
} catch ('Illuminate'Database'QueryException $exception) {
    // You can check get the details of the error using `errorInfo`:
    $errorInfo = $exception->errorInfo;
    // Return the response to the client..
}

我更喜欢为其他地方无法处理的意外事件保留try/catch。在这种情况下,您可以将验证作为第一个度量,将异常处理程序作为备份度量。

如果表单请求失败,则会闪烁错误消息,并将用户返回到上一页(表单提交的位置),您可以优雅地处理这些消息。验证请求

// First line of defence - gracefully handle
// Controller 
public function store(MFUserRequest $request)
{
    // The incoming request is valid...
    MFUser::create(array(...));
}
// Form Request
class MFUserRequest extends Request 
{
    public function rules()
    {
        return [
            'email' => 'required|email|unique:users,email',
        ];
    }    
}

在其他地方,在App''Exceptions目录中,您有一个异常处理程序类,它可以捕获各种错误。当你无法优雅地处理它时,可以使用这个。

// Second line of defence - something was missed, and a model was  
// created without going via the above form request
namespace App'Exceptions;
class Handler extends ExceptionHandler
{
    public function render($request, Exception $e)
    {        
        if($e instanceof QueryException) {
            // log it or similar. then dump them back on the dashboard or general something bad
            // has happened screen
            return redirect()->route('/dashboard');
        }
    }
}

只需使用try / catch块。

use Illuminate'Database'QueryException;
// ...
try {
    // DB query goes here.
} catch (QueryException $e) {
    // Logics in case there are QueryException goes here
}
// ...

Try and Catch有些东西可能会帮助你并想象为所有这些创建try-catch,但最好使用Laravel Exceptions Handler来处理所有QueryException,因为它可以让你轻松地将exeception全局化!

让我们试试吧!,打开App'Exception'Handler.php,在呈现方法中,你可以像这样写一个

public function render($request, Throwable $exception)
{
   if ($request->ajax() || $request->wantsJson()) {
      if ($exception instanceof QueryException) {
          // example algo for make response
          return response()->json(['message' => 'xxx'], 403);
      }
   }
   return parent::render($request, $exception);
}

之后,u可以为查询触发的每个错误请求获取xxx-json