Just change the exception handler from the framework , located at app\Exceptions\Handler.php
, changing the method that renders exceptions, leaving it like this:
>
public function render($request, Exception $e)
{
$json = [
'success' => false,
'error' => [
'code' => $e->getCode(),
'message' => $e->getMessage(),
],
];
return response()->json($json, 400);
}
Basically every time an exception occurs you are getting some data, such as error code and its message, and returning in JSON . In the production environment this would never appear, since you disable debug
.
But note that this will also bar a request
with wrong validation, and you will not be allowed to pick up the validation messages, to circumvent this we need to respond in json in that case only when the error code is nonzero, because the zero error refers to the validation error, then the code looks like this:
public function render($request, Exception $e)
{
if($e->getCode() != 0) {
$json = [
'success' => false,
'error' => [
'code' => $e->getCode(),
'message' => $e->getMessage(),
],
];
return response()->json($json, 400);
}
return parent::render($request, $e);
}