创建时的Laravel模型错误处理

ses*_*360 5 php laravel

我想使用Eloquent创建这样的数据库条目:

   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
    ));
Run Code Online (Sandbox Code Playgroud)

除了将完全相同的数据放入字段中(这是预期的,因为不应有重复项)的情况之外,它工作得很好。然后我得到了QueryExecption。

但是,如何在此处正确执行错误处理以检查是否发生此查询异常,以便随后可以通过json将服务器的响应返回给客户端?

Luí*_*ruz 7

只需将该代码包装在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..
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ris 5

我更喜欢保留try/catch's 来应对其他地方无法处理的意外事件。在这种情况下,您可以利用验证作为第一个措施,并使用异常处理程序作为备用措施。

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

// 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',
        ];
    }    
}
Run Code Online (Sandbox Code Playgroud)

在其他地方,在您的 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');
        }
    }
}
Run Code Online (Sandbox Code Playgroud)