laravel 出错时不 return 调用堆栈
laravel do not return call stack on error
例如在我的 REST Json API 中:当我使用路由模型绑定调用路由并传递无效 ID 时,我得到:
{
"message": "No query results for model [App\Models\User].",
"exception": "Symfony\Component\HttpKernel\Exception\NotFoundHttpException",
"file": "D:\allianz\backend\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php",
"line": 199,
"trace": [
{ ...
但是我不想向 API 消费者展示这个。 (或者只是消息)。
您总是可以在 App\Exceptions\Handler.php
中捕获异常
使用以下命令将异常导入 class:
use \Illuminate\Database\Eloquent\ModelNotFoundException;
并在渲染方法中添加
if ($e instanceof ModelNotFoundException) {
return response()->json([
'message' => 'Record not found', //or modify it to display whatever message you want here
], 404);
}
你 APP_ENV 变量设置在什么位置?我相信调用堆栈在生产时不会返回。
虽然这个问题是上个世纪问的,但我还是想留个答案给Laravel 9.7.0。
展示了如何全局设置在 http-responses.
中应如何呈现未处理的异常
我将代码稍微更改为 return exception-info 而没有 stack-trace:
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
$this->renderable(function (Throwable $e, $request) {
$env = config("app.env");
$msg = $e->getMessage() . " in file '" . $e->getFile() . "' on line '" . $e->getLine() . "'";
if ($request->is('api/*')) {
if (strcmp($env, "debug") == 0) {
return response()->make($msg.$e->getTraceAsString(), 500);
} else {
return response()->json([
'message' => $msg
], 500);
}
}
});
}
因此,如果我在 .env-file 中设置 APP_ENV=debug
,堆栈跟踪将添加到响应 text-message。它是文本,因为我没有测试堆栈跟踪如何与消费者 json 解释器混淆。如果 APP_ENV != debug,则响应是一个 json 对象,其中 message-value 包含消息、文件和行号。
例如在我的 REST Json API 中:当我使用路由模型绑定调用路由并传递无效 ID 时,我得到:
{
"message": "No query results for model [App\Models\User].",
"exception": "Symfony\Component\HttpKernel\Exception\NotFoundHttpException",
"file": "D:\allianz\backend\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php",
"line": 199,
"trace": [
{ ...
但是我不想向 API 消费者展示这个。 (或者只是消息)。
您总是可以在 App\Exceptions\Handler.php
中捕获异常使用以下命令将异常导入 class:
use \Illuminate\Database\Eloquent\ModelNotFoundException;
并在渲染方法中添加
if ($e instanceof ModelNotFoundException) {
return response()->json([
'message' => 'Record not found', //or modify it to display whatever message you want here
], 404);
}
你 APP_ENV 变量设置在什么位置?我相信调用堆栈在生产时不会返回。
虽然这个问题是上个世纪问的,但我还是想留个答案给Laravel 9.7.0。
我将代码稍微更改为 return exception-info 而没有 stack-trace:
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
$this->renderable(function (Throwable $e, $request) {
$env = config("app.env");
$msg = $e->getMessage() . " in file '" . $e->getFile() . "' on line '" . $e->getLine() . "'";
if ($request->is('api/*')) {
if (strcmp($env, "debug") == 0) {
return response()->make($msg.$e->getTraceAsString(), 500);
} else {
return response()->json([
'message' => $msg
], 500);
}
}
});
}
因此,如果我在 .env-file 中设置 APP_ENV=debug
,堆栈跟踪将添加到响应 text-message。它是文本,因为我没有测试堆栈跟踪如何与消费者 json 解释器混淆。如果 APP_ENV != debug,则响应是一个 json 对象,其中 message-value 包含消息、文件和行号。