2016-03-26 21 views
0

Böyle bir DB giriş oluşturmak için anlamlı kullanmak istediğiniz Oluşturma: Bu durum dışında, iyi çalışıyorlaravel Modeli Hata İşleme

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 
    )); 

, tam olarak aynı veri alanlarının içine koymak durumunda hangi yinelenen olmaması gerektiği için bekleniyor. Sonra QueryExecption alıyorum.

Ancak bu sorgu istisnasının oluşup oluşmadığını kontrol etmek için hata işlemeyi düzgün bir şekilde nasıl gerçekleştiririm? Böylece sunucumdan istemciye json aracılığıyla yanıt gönderebilir miyim?

cevap

0

Sadece bu kodu bir try - catch satırına sarın. Böyle bir şey:

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.. 
} 
0

Basitçe try/catch bloğun faydalanmak.

use Illuminate\Database\QueryException; 

// ... 

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

// ... 
1

ben başka bir yerde ele alınamaz beklenmedik olaylar için try/catch 's ayırmak tercih ederim. Bu durumda, bir ilk ölçü olarak validasyon ve bir yedek önlem olarak istisna eylemcisi kullanabilirsiniz.

Form isteği başarısız olursa, hata iletileri yanıp söner ve kullanıcı önceki sayfaya (formun gönderildiği yer) döndürülür ve iletileri düzgün bir şekilde işleyebilirsiniz. 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', 
     ]; 
    }  
} 

Başka bir yerde, App \ İstisnalar dizinde tüm çeşitli hatalar için bir av olabilir istisna işleyicisi sınıf var. Bunu daha da küçümsemediyseniz, bunu kullanın.

// 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'); 
     } 
    } 
} 
İlgili konular