Ich bin neu in Laravel und in Lumen. Ich möchte sicherstellen, dass ich immer nur ein JSON-Objekt als Ausgabe erhalte. Wie kann ich das in Lumen machen?
Ich kann eine JSON-Antwort mit response()->json($response);
erhalten. Aber wenn ein Fehler auftritt, gibt die API mir text/html
Fehler. Aber ich möchte nur application/json
Antworten.
Danke im Voraus.
Sie müssen Ihren Ausnahmehandler (app/Exceptions/Handler.php
) anpassen, um die gewünschte Antwort zurückzugeben.
Dies ist ein sehr einfaches Beispiel dafür, was getan werden kann.
public function render($request, Exception $e)
{
$rendered = parent::render($request, $e);
return response()->json([
'error' => [
'code' => $rendered->getStatusCode(),
'message' => $e->getMessage(),
]
]);
}
Eine genauere Lösung basierend auf @ Waders Antwort kann sein:
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());
}
Ich mache das nur, wenn ich mit APIs arbeite
<?php namespace App\Exceptions;
use Exception;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Illuminate\Http\Response;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param Exception $e
*
* @throws Exception
*/
public function report(Exception $e): void
{
parent::report($e);
}
/**
* @param \Illuminate\Http\Request $request
* @param Exception $e
*
* @return \Illuminate\Http\JsonResponse|Response
*/
public function render($request, Exception $e)
{
if (env('APP_DEBUG')) {
return parent::render($request, $e);
}
$status = Response::HTTP_INTERNAL_SERVER_ERROR;
if ($e instanceof HttpResponseException) {
$status = Response::HTTP_INTERNAL_SERVER_ERROR;
} elseif ($e instanceof MethodNotAllowedHttpException) {
$status = Response::HTTP_METHOD_NOT_ALLOWED;
$e = new MethodNotAllowedHttpException([], 'HTTP_METHOD_NOT_ALLOWED', $e);
} elseif ($e instanceof NotFoundHttpException) {
$status = Response::HTTP_NOT_FOUND;
$e = new NotFoundHttpException('HTTP_NOT_FOUND', $e);
} elseif ($e instanceof AuthorizationException) {
$status = Response::HTTP_FORBIDDEN;
$e = new AuthorizationException('HTTP_FORBIDDEN', $status);
} elseif ($e instanceof \Dotenv\Exception\ValidationException && $e->getResponse()) {
$status = Response::HTTP_BAD_REQUEST;
$e = new \Dotenv\Exception\ValidationException('HTTP_BAD_REQUEST', $status, $e);
} elseif ($e) {
$e = new HttpException($status, 'HTTP_INTERNAL_SERVER_ERROR');
}
return response()->json([
'status' => $status,
'message' => $e->getMessage()
], $status);
}
}
Als MTVS answer können Sie sogar die JsonResponse-Klasse verwenden, um Ihre Antwort zu formatieren, und sie als statisches Element innerhalb der Rendermethode verwenden, ohne sie wie folgt in den Handler-Namespace zu importieren:
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 \Illuminate\Http\JsonResponse)
{
return $parentRender;
}
return new \Illuminate\Http\JsonResponse([
'message' => $e instanceof HttpException
? $e->getMessage()
: 'Server Error',
], $parentRender->status());
}