如何在 Laravel 中获取没有 HTML 的原始异常消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30764466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get raw Exception Message without HTML in Laravel?
提问by Kamil Davudov
I make ajax requests to Laravel backend.
我向 Laravel 后端发出 ajax 请求。
In backend I check request data and throw some exceptions. Laravel, by default, generate html pages with exception messages.
在后端,我检查请求数据并抛出一些异常。Laravel 默认会生成带有异常消息的 html 页面。
I want to respond just raw exception message not any html.
我只想响应原始异常消息而不是任何 html。
->getMessage()
doesn't work. Laravel, as always, generate html.
->getMessage()
不起作用。Laravel 一如既往地生成 html。
What shoud I do?
我该怎么办?
回答by Limon Monte
In Laravel 5 you can catch exceptions by editing the render
method in app/Exceptions/Handler.php
.
在Laravel 5中,您可以通过编辑捕获异常render
的方法app/Exceptions/Handler.php
。
If you want to catch exceptions for all AJAX requests you can do this:
如果您想捕获所有 AJAX 请求的异常,您可以这样做:
public function render($request, Exception $e)
{
if ($request->ajax()) {
return response()->json(['message' => $e->getMessage()]);
}
return parent::render($request, $e);
}
This will be applied to ANY exception in AJAX requests.If your app is sending out an exception of App\Exceptions\MyOwnException
, you check for that instance instead.
这将应用于 AJAX 请求中的任何异常。如果您的应用发出 异常App\Exceptions\MyOwnException
,则改为检查该实例。
public function render($request, Exception $e)
{
if ($e instanceof \App\Exceptions\MyOwnException) {
return response()->json(['message' => $e->getMessage()]);
}
return parent::render($request, $e);
}