Laravel Lumen Ensure JSON response
You'll need to adjust your exception handler (app/Exceptions/Handler.php
) to return the response you want.
This is a very basic example of what can be done.
public function render($request, Exception $e)
{
$rendered = parent::render($request, $e);
return response()->json([
'error' => [
'code' => $rendered->getStatusCode(),
'message' => $e->getMessage(),
]
], $rendered->getStatusCode());
}
A more accurate solution based on @Wader's answer can be:
use Illuminate\Http\JsonResponse;
public function render($request, Exception $e)
{
$parentRender = parent::render($request, $e);
// if parent returns a JsonResponse
// for example in case of a ValidationException
if ($parentRender instanceof JsonResponse)
{
return $parentRender;
}
return new JsonResponse([
'message' => $e instanceof HttpException
? $e->getMessage()
: 'Server Error',
], $parentRender->status());
}