在laravel中,我们可以按如下方式处理异常:
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException or $exception instanceof NotFoundHttpException)
{
if($request->ajax() || $request->wantsJson()) {
return response()->json([
'message' => 'Record not found',
], 404);
}
}
return parent::render($request, $exception);
}
但是,当存在内部服务器错误时,应用程序将在生产中返回Whoops something went wrong
页,如果在调试中返回堆栈跟踪。
使用需要 json 的 api 时如何处理内部服务器错误?
您实际上可以在render()
(app/Exceptions/Handler.php)方法中对ErrorException
添加另一个检查:
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException or $exception instanceof NotFoundHttpException)
{
if($request->ajax() || $request->wantsJson())
{
return response()->json([
'message' => 'Record not found',
], 404);
}
}
// ==> Add this check
if ($exception instanceof ErrorException)
{
if($request->ajax() || $request->wantsJson())
{
return response()->json([
'message' => 'Something went wrong on our side',
], 500);
}
}
return parent::render($request, $exception);
}
这是我的解决方法:
if (!$this->isHttpException($exception))
{
if($request->ajax() || $request->wantsJson())
{
return response()->json([
'message' => 'Something went wrong on our side',
], 500);
}
}
我遇到了类似的问题,但这是我的.htaccess文件,我没有正确的配置。(我的环境是Laravel 5.6,Bitmani LAMP)
.htaccess 必须具有以下特性:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
RewriteBase /
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
这对我有用,在我的 API 中修复了我的"内部服务器错误 (500)"。一个建议是检查 apache 日志(error_log 和 access_log),他们可以为您提供更多信息。
我希望它对你有所帮助。