gpt4 book ai didi

Laravel API,如何正确处理错误

转载 作者:行者123 更新时间:2023-12-04 01:39:13 26 4
gpt4 key购买 nike

任何人都知道在 Laravel 中处理错误的最佳方法是什么,有什么规则或要遵循的东西吗?

目前我正在这样做:

public function store(Request $request)
{
$plate = Plate::create($request->all());

if ($plate) {
return $this->response($this->plateTransformer->transform($plate));
} else {
// Error handling ?
// Error 400 bad request
$this->setStatusCode(400);
return $this->responseWithError("Store failed.");
}
}

而 setStatusCode 和 responseWithError 来自我的 Controller 的父亲:
public function setStatusCode($statusCode)
{
$this->statusCode = $statusCode;

return $this;
}

public function responseWithError ($message )
{
return $this->response([
'error' => [
'message' => $message,
'status_code' => $this->getStatusCode()
]
]);

}

但这是处理 API 错误的好方法吗,我看到了一些不同的处理网络错误的方法,最好的方法是什么?

谢谢。

最佳答案

试试这个,我在我的项目中使用过它 (应用程序/异常/Handler.php)

public function render($request, Exception $exception)
{
if ($request->wantsJson()) { //add Accept: application/json in request
return $this->handleApiException($request, $exception);
} else {
$retval = parent::render($request, $exception);
}

return $retval;
}

现在处理 Api 异常
private function handleApiException($request, Exception $exception)
{
$exception = $this->prepareException($exception);

if ($exception instanceof \Illuminate\Http\Exception\HttpResponseException) {
$exception = $exception->getResponse();
}

if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
$exception = $this->unauthenticated($request, $exception);
}

if ($exception instanceof \Illuminate\Validation\ValidationException) {
$exception = $this->convertValidationExceptionToResponse($exception, $request);
}

return $this->customApiResponse($exception);
}

在自定义 Api 处理程序响应之后
private function customApiResponse($exception)
{
if (method_exists($exception, 'getStatusCode')) {
$statusCode = $exception->getStatusCode();
} else {
$statusCode = 500;
}

$response = [];

switch ($statusCode) {
case 401:
$response['message'] = 'Unauthorized';
break;
case 403:
$response['message'] = 'Forbidden';
break;
case 404:
$response['message'] = 'Not Found';
break;
case 405:
$response['message'] = 'Method Not Allowed';
break;
case 422:
$response['message'] = $exception->original['message'];
$response['errors'] = $exception->original['errors'];
break;
default:
$response['message'] = ($statusCode == 500) ? 'Whoops, looks like something went wrong' : $exception->getMessage();
break;
}

if (config('app.debug')) {
$response['trace'] = $exception->getTrace();
$response['code'] = $exception->getCode();
}

$response['status'] = $statusCode;

return response()->json($response, $statusCode);
}

常加Accept: application/json在您的 api 或 json 请求中。

关于Laravel API,如何正确处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51065170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com