2016-07-26 40 views
2

使用Laravel 5,我想發送自定義abort()消息。
例如,如果用戶沒有所需的操作權限,
我想abort(401, "User can't perform this actions")
目前,當我這樣做時,響應文本是HTML頁面而不是消息。
如何僅返回消息?Laravel 5:自定義中止()消息

注意:我不想傳遞不同的視圖,但只傳遞自定義消息。

+0

的可能的複製[傳遞自定義消息(或任何其他數據),以Laravel 404.blade.php](http://stackoverflow.com/questions/29163564/pass-a-custom-message-or-any-other-data-to-laravel-404-blade-php) – Tim

回答

0

您可以在此處理所有錯誤異常app/Exceptions/Handler.php Class根據您的要求。

在你的情況下,只需更換渲染功能,這個

public function render($request, Exception $e) 
{ 
    return $e->getMessage(); 
    //For Json 
    //return response()->json(['message' => $e->getMessage()]); 
} 
+0

我試過了,但是它不會到達瀏覽器中的.catch。 –

+0

我沒有得到你「它不會到達瀏覽器中的.catch」意思是 – vijaykumar

+0

使用Promise:promise.then(this._thenMethod).catch(this._defaultCatcher); –

0

首先在你的頭文件或在頁面中添加錯誤消息,你想顯示類似消息:

@if($errors->has()) 
    @foreach ($errors->all() as $error) 
     <div>{{ $error }}</div> 
    @endforeach 
@endif 

而在控制器,你可以做這樣的東西(如):

public function store(){ 
    if(user is not permitted to access this action) // check user permission here 
    { 
     return redirect()->back()->withErrors("User can't perform this actions"); 
    } 
} 

您可以重定向回w ^第i個錯誤消息

+0

我應該補充一點,我說的是$ .ajax調用,而不是瀏覽器重定向。 –

0

Handler.php我改變了功能:

public function render($request, Exception $e) 
{ 
    $response = parent::render($request, $e); 

    if (method_exists($e, "getStatusCode")) { 
     if ($e->getStatusCode() == 401) { 
      $response->setContent($e->getMessage()); 
     } 
    } 

    return $response; 
} 
1

答案是簡單地使用響應()輔助方法代替中止的()。語法如下。

return response("User can't perform this action.", 401); 
+0

但是,'return'會繼續執行調用者。使用'abort',我不想繼續使用任何業務邏輯。 –

+0

哦,這也不起作用,至少在我的應用程序沒有。'response('',400) - > json('some message')'仍然返回HTML頁面。 –

0

應該能夠使用模板如下:

{{ $exception->getMessage() }} 
3

根據Laravel 5.4文檔:

https://laravel.com/docs/5.4/errors#http-exceptions

您可以使用abort傭工迴應文本:

abort(500, 'Something went wrong'); 

和使用resources/views/errors/500.blade.php$exception->getMessage()顯示它:

Error message: {{ $exception->getMessage() }} 
+0

這將是正確的方法,但是如何在此消息中添加「換行」字符或換行符(或更好的子彈)? – blamb

+1

@blamb如果郵件包含HTML代碼(如
),請使用{! !!}語法而不是{{}}來顯示非轉義內容。 – Kenny