使用Laravel 5,我想發送自定義abort()
消息。
例如,如果用戶沒有所需的操作權限,
我想abort(401, "User can't perform this actions")
。
目前,當我這樣做時,響應文本是HTML頁面而不是消息。
如何僅返回消息?Laravel 5:自定義中止()消息
注意:我不想傳遞不同的視圖,但只傳遞自定義消息。
使用Laravel 5,我想發送自定義abort()
消息。
例如,如果用戶沒有所需的操作權限,
我想abort(401, "User can't perform this actions")
。
目前,當我這樣做時,響應文本是HTML頁面而不是消息。
如何僅返回消息?Laravel 5:自定義中止()消息
注意:我不想傳遞不同的視圖,但只傳遞自定義消息。
您可以在此處理所有錯誤異常app/Exceptions/Handler.php Class根據您的要求。
在你的情況下,只需更換渲染功能,這個
public function render($request, Exception $e)
{
return $e->getMessage();
//For Json
//return response()->json(['message' => $e->getMessage()]);
}
我試過了,但是它不會到達瀏覽器中的.catch。 –
我沒有得到你「它不會到達瀏覽器中的.catch」意思是 – vijaykumar
使用Promise:promise.then(this._thenMethod).catch(this._defaultCatcher); –
首先在你的頭文件或在頁面中添加錯誤消息,你想顯示類似消息:
@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個錯誤消息
我應該補充一點,我說的是$ .ajax調用,而不是瀏覽器重定向。 –
在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;
}
答案是簡單地使用響應()輔助方法代替中止的()。語法如下。
return response("User can't perform this action.", 401);
但是,'return'會繼續執行調用者。使用'abort',我不想繼續使用任何業務邏輯。 –
哦,這也不起作用,至少在我的應用程序沒有。'response('',400) - > json('some message')'仍然返回HTML頁面。 –
應該能夠使用模板如下:
{{ $exception->getMessage() }}
根據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() }}
的可能的複製[傳遞自定義消息(或任何其他數據),以Laravel 404.blade.php](http://stackoverflow.com/questions/29163564/pass-a-custom-message-or-any-other-data-to-laravel-404-blade-php) – Tim