创建时 Laravel 模型错误处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36241924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:28:43  来源:igfitidea点击:

Laravel Model Error Handling when Creating

phplaravel

提问by sesc360

I want to use Eloquent to create a DB entry like this:

我想使用 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
    ));

It works well, except for the case, when exactly the same data is put into the fields, which is expected, as there should be no duplicate. I get the QueryExecption then.

它工作得很好,除了这种情况,当完全相同的数据放入字段时,这是预期的,因为不应该有重复。然后我得到了 QueryExecption。

But how do I properly perform error handling here to check if this query exception occurs so I can return a response from my server to the client via json then?

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

回答by Luís Cruz

Just wrap that code in a try-catchblock. Something like this:

只需将该代码包装在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..
}

回答by Chris

I prefer to reserve try/catch's for unexpected events that can't be handled elsewhere. In this case, you can utilise validation as a first measure, and the exception handler as a backup measure.

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

If the form request fails, the error messages are flashed and the user is returned to the previous page (where the form was submitted) and you can handle the messages gracefully. Validation requests

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

// 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',
        ];
    }    
}

Elsewhere, in your App\Exceptions directory you have the exception handler class that can be a catch all for various errors. Use this, when you haven't been able to gracefully handle it further down.

在其他地方,在您的 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');
        }
    }
}

回答by James Akwuh

Simply make use of try / catchblock.

只需使用try / catch块。

use Illuminate\Database\QueryException;

// ...

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

// ...