Php Laravel 5:自定义中止()消息
使用Laravel 5,我想发送一条自定义的Php Laravel 5:自定义中止()消息,php,laravel,laravel-5,Php,Laravel,Laravel 5,使用Laravel 5,我想发送一条自定义的abort()消息。 例如,如果用户没有操作所需的权限, 我想中止(401,“用户无法执行此操作”) 目前,当我这样做时,响应文本是HTML页面,而不是消息。 我怎样才能只返回消息 注意:我不想传递其他视图,只想传递自定义消息。您可以根据需要在app/exceptions/Handler.php类中处理所有错误异常 在您的情况下,只需将渲染函数替换为 public function render($request, Exception $e) {
abort()
消息。例如,如果用户没有操作所需的权限,
我想
中止(401,“用户无法执行此操作”)
目前,当我这样做时,响应文本是HTML页面,而不是消息。
我怎样才能只返回消息
注意:我不想传递其他视图,只想传递自定义消息。您可以根据需要在app/exceptions/Handler.php类中处理所有错误异常 在您的情况下,只需将渲染函数替换为
public function render($request, Exception $e)
{
return $e->getMessage();
//For Json
//return response()->json(['message' => $e->getMessage()]);
}
首先,在头文件或要显示消息的页面中添加错误消息,如下所示:
@if($errors->has())
@foreach ($errors->all() as $error)
<div>{{ $error }}</div>
@endforeach
@endif
您可以在
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;
}
答案只是使用response()helper方法,而不是abort()。语法如下
return response("User can't perform this action.", 401);
应能够在模板中使用以下内容:
{{ $exception->getMessage() }}
根据Laravel 5.4文件: 您可以对响应文本使用
abort
helper:
abort(500, 'Something went wrong');
并在resources/views/errors/500.blade.php
中使用$exception->getMessage()
来显示它:
Error message: {{ $exception->getMessage() }}
您可以将响应包装在abort中,这将停止执行并返回响应。如果希望它是JSON,那么添加
->JSON()代码>
我试过了,但是它无法到达浏览器中的.catch。我没有理解“它无法到达浏览器中的.catch”的意思是使用承诺:Promise.then(this.\thenMethod).catch(this.\u defaultCatcher);可以我不确定,但尝试将响应作为json发送,如返回响应()->json(['message'=>$e->getMessage()]);我应该补充一点,我说的是$.ajax调用,而不是浏览器重定向。但是,return
的可能重复项将继续执行调用方。使用中止
,我不想继续任何业务逻辑。哦,这也不起作用,至少在我的应用程序中不起作用response(“”,400)->json('some message')
仍然返回HTML页面。这是正确的方法,但我如何在消息中添加“换行符”字符或换行符(或更好的项目符号)?@b如果消息包含HTML代码(如
),请使用{!!!!}语法而不是{{}在laravel 5.7@section('message'),\uu($exception->getMessage()?$exception->getMessage():“哎哟,我们的服务器出了问题。”)
Error message: {{ $exception->getMessage() }}
# Regular response
abort( response('Unauthorized', 401) );
# JSON response
abort( response()->json('Unauthorized', 401) );