【发布时间】:2018-09-27 15:40:53
【问题描述】:
在 Laravel 5.6 上,当我调用受 auth:api 中间件保护的路由时,我收到 400 响应错误,而不是我预期的 401。
api.php:
Route::middleware('auth:api')->group(function() {
//...
}
还有异常处理程序:
public function render($request, Exception $e)
{
// If the request wants JSON (AJAX doesn't always want JSON)
if ($request->wantsJson()) {
// Define the response
$response = [
'errors' => 'Sorry, something went wrong.'
];
// If the app is in debug mode
if (config('app.debug')) {
// Add the exception class name, message and stack trace to response
$response['exception'] = get_class($e); // Reflection might be better here
$response['message'] = $e->getMessage();
$response['trace'] = $e->getTrace();
}
// Default response of 400
$status = 400;
// If this exception is an instance of HttpException
if ($this->isHttpException($e)) {
// Grab the HTTP status code from the Exception
$status = $e->getStatusCode();
}
// Return a JSON response with the response array and status code
return response()->json($response, $status);
}
// Default to the parent class' implementation of handler
return parent::render($request, $e);
}
错误:
{
"errors": "Sorry, something went wrong.",
"exception": "Illuminate\\Auth\\AuthenticationException",
"message": "Unauthenticated.",
"trace": [Here's the trace]
}
在this answer 中可以看到预期的行为,但问题有所不同。
为什么我得到的是 400 而不是只有 message 的 401?
【问题讨论】:
标签: php laravel api exception exception-handling