我向 Laravel 后端发出 ajax 请求。
在后端,我检查请求数据并抛出一些异常。 默认情况下,Laravel 会生成带有异常消息的 html 页面。
我只想响应原始异常消息,而不是任何 html。
->getMessage()
不起作用。 Laravel 一如既往地生成 html。
我该怎么办?
最佳答案
在 Laravel 5 中,您可以通过编辑 app/Exceptions/Handler.php
中的 render
方法来捕获异常。
如果你想捕获所有 AJAX 请求的异常,你可以这样做:
public function render($request, Exception $e)
{
if ($request->ajax()) {
return response()->json(['message' => $e->getMessage()]);
}
return parent::render($request, $e);
}
这将应用于 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);
}
关于php - 如何在 Laravel 中获取没有 HTML 的原始异常消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30764466/