I have only API laravel project. If I turn the debug mode off in .env
file by setting APP_DEBUG=false
, my application throws Server error
for the errors that shouldn’t be shown to user.
But it return json response like this:
{
"message": "Server Error"
}
I want to add code key to it ass well. What I am trying to achieve:
{
"code": 500,
"message": "Server Error"
}
What I tried so far (register
method of Handler
):
$this->renderable(function (Throwable|Exception $e) {
return response()->json([
'code' => $e->getCode(),
'message' => $e->getMessage()
], $e->getCode());
});
But this will return exception message that shouldn’t shown to user. I need smth like this:
$this->renderable(function (Throwable|Exception $e) {
// ReportableException doesn't exist in laravel
if($e instanceof ReportableException){
return response()->json([
'code' => 500,
'message' => 'Server error'
], 500);
}
return response()->json([
'code' => $e->getCode(),
'message' => $e->getMessage()
], $e->getCode());
});
2
Answers
I found out that there is
isHttpException
method that is used to know if exception is reportable or unreportableto user. So that is my solution:You do have access to HttpResponseException so you can do something like this:
So it will look something like this:
Hopefully this works for you.