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());
});
CodePudding user response:
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:
$this->renderable(function (Throwable $e) {
if (!$this->isHttpException($e)){
return response()->json([
'code' => 500,
'message' => "Internal server error"
], 500);
}
$code = $e->getCode() == 0 ? 500 : $e->getCode();
return response()->json([
'code' => $code,
'message' => $e->getMessage()
], $code);
});
CodePudding user response:
You do have access to HttpResponseException so you can do something like this:
if ($exception instanceof \Illuminate\Http\Exception\HttpResponseException) {
//Can use this directly for details
$exception = $exception->getResponse();
//Or handle the exception manually
switch ($exception->getStatusCode()) {
case 401:
$response->code = 401;
$response->message = 'Unauthorized';
break;
case 403:
$response->code = 403;
$response->message = 'Unauthorized';
break;
case 404:
$response->code = 404;
$response->message = 'Not Found';
break;
case 405:
$response->code = 405;
$response->message = 'Unauthorized';
break;
case 422:
$response->code = 422;
$response->message = '??';
break;
default:
$response->code = 500;
$response->message = '??';
break;
}
}
So it will look something like this:
if($e instanceof \Illuminate\Http\Exception\HttpResponseException){
return response()->json([
'code' => $e->getStatusCode(),
'message' => 'Server error'
], $e->getStatusCode());
}
Hopefully this works for you.