2016-02-11 27 views
10

Ben laravel 5'te laravel 5.AJAX hatalarını Laravel denetleyicisinden nasıl iade edilir?

ile REST API inşa ediyorum, belirli bir rota işlenecektir önce yerine getirilmesi gereken doğrulama kuralları tanımlamak için App\Http\Requests\Request alt sınıf. Örneğin:

<?php 

namespace App\Http\Requests; 

use App\Http\Requests\Request; 

class BookStoreRequest extends Request { 

    public function authorize() { 
     return true; 
    } 

    public function rules() { 
     return [ 
      'title' => 'required', 
      'author_id' => 'required' 
     ]; 
    } 
} 

bir istemci AJAX isteği ile ilgili yol yükler ve BookStoreRequest kurallarına uymuyor istek, bu automagicallylar JSON nesnesi olarak hata (ler) döndürür bulursa

. Örneğin: istek zaten kabul edilmiş ve kontrolöre devredilmiştir sonra

{ 
    "title": [ 
    "The title field is required." 
    ] 
} 

Ancak Request::rules() yöntem yalnızca doğrulayabilir giriş-ve giriş geçerli olsa bile, başka hata türlü ortaya çıkabilecek. Örneğin, kontrolör açılamaz nedense ama dosya için bir dosyaya yeni kitap bilgilerini yazmak için ihtiyacı olduğunu varsayalım:

<?php 

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 

use App\Http\Requests; 
use App\Http\Controllers\Controller; 

use App\Http\Requests\BookCreateRequest; 

class BookController extends Controller { 

    public function store(BookStoreRequest $request) { 

     $file = fopen('/path/to/some/file.txt', 'a'); 

     // test to make sure we got a good file handle 
     if (false === $file) { 
      // HOW CAN I RETURN AN ERROR FROM HERE? 
     } 

     fwrite($file, 'book info goes here'); 
     fclose($file); 

     // inform the browser of success 
     return response()->json(true); 

    } 

} 

Açıkçası, ben sadece die() olabilir, ama bu süper çirkin. Hata iletimi, doğrulama hatalarıyla aynı biçimde döndürmeyi tercih ederim. Şunun gibi:

{ 
    "myErrorKey": [ 
    "A filesystem error occurred on the server. Please contact your administrator." 
    ] 
} 

ben kendi JSON nesnesi oluşturmak ve dönüş o-ama emin adımlarla laravel bu doğal destekler olabilir.

Bunu yapmanın en iyi/en temiz yolu nedir? Ya da bir Laravel REST API'sinden çalışma zamanı (validate-time'ın aksine) hatalarını döndürmenin daha iyi bir yolu var mı?

+0

Neden sadece bir "return response() -> json (['error' => 'Özel mesajınız']);'? –

+0

Özel bir json yanıt sınıfı oluşturabilirsiniz – Digitlimit

+0

'dönüş yanıtı() -> json()' 200 Tamam ile döndürür. Uygun olmayan 200 yanıt kodunu kullanmak istiyorum (ör. 500 Dahili Sunucu Hatası). Evet, bunu da el ile yapabilirdim - Laravel'in bunu yapmanın daha yerleşik bir yolunu zaten sağladığını varsaydım. Belki bu yanlış bir varsayımdır. – greenie2600

cevap

13

Sen olarak aşağıya json yanıt olarak durum kodu ayarlayabilirsiniz:

return Response::json(['error' => 'Error msg'], 404); // Status code here 

Ya da sadece yardımcı işlevini kullanarak:

return response()->json(['error' => 'Error msg'], 404); // Status code here 
+0

response() işlevini kullanın, $ response() değil –

3

birçok şekilde yapabilirsiniz.

İlk olarak, bir durum kodu sağlayarak basit response()->json() kullanabilirsiniz: Her hata bir json yanıtı olduğundan emin olmak için bir daha complexe şekilde

return response()->json(/** response **/, 401); 

Ya da, bir istisna işleyicisi ayarlayabilirsiniz özel bir istisna yakala ve json'a dön.

Açık App\Exceptions\Handler ve aşağıdakileri yapın:

class Handler extends ExceptionHandler 
{ 
    /** 
    * A list of the exception types that should not be reported. 
    * 
    * @var array 
    */ 
    protected $dontReport = [ 
     HttpException::class, 
     HttpResponseException::class, 
     ModelNotFoundException::class, 
     NotFoundHttpException::class, 
     // Don't report MyCustomException, it's only for returning son errors. 
     MyCustomException::class 
    ]; 

    public function render($request, Exception $e) 
    { 
     // This is a generic response. You can the check the logs for the exceptions 
     $code = 500; 
     $data = [ 
      "error" => "We couldn't hadle this request. Please contact support." 
     ]; 

     if($e instanceof MyCustomException) { 
      $code = $e->getStatusCode(); 
      $data = $e->getData(); 
     } 

     return response()->json($data, $code); 
    } 
} 

Bu uygulamada fırlatılacak herhangi bir json dönecektir. Şimdi, uygulama/İstisnalar örneğin, MyCustomException oluşturun: Biz şimdi sadece MyCustomException veya json hata dönmek MyCustomException uzanan herhangi istisna kullanabilirsiniz

class MyCustomException extends Exception { 

    protected $data; 
    protected $code; 

    public static function error($data, $code = 500) 
    { 
     $e = new self; 
     $e->setData($data); 
     $e->setStatusCode($code); 

     throw $e; 
    } 

    public function setStatusCode($code) 
    { 
     $this->code = $code; 
    } 

    public function setData($data) 
    { 
     $this->data = $data; 
    } 


    public function getStatusCode() 
    { 
     return $this->code; 
    } 

    public function getData() 
    { 
     return $this->data; 
    } 
} 

.

public function store(BookStoreRequest $request) { 

    $file = fopen('/path/to/some/file.txt', 'a'); 

    // test to make sure we got a good file handle 
    if (false === $file) { 
     MyCustomException::error(['error' => 'could not open the file, check permissions.'], 403); 

    } 

    fwrite($file, 'book info goes here'); 
    fclose($file); 

    // inform the browser of success 
    return response()->json(true); 

} 

Şimdi MyCustomException yoluyla atılan sadece istisnalar bir json hata döndürür, ancak diğer istisnası genel atılmış.

İlgili konular