Php 受身份验证保护的路由在未经身份验证时返回400错误
在Laravel5.6上,当我调用受Php 受身份验证保护的路由在未经身份验证时返回400错误,php,laravel,api,exception,exception-handling,Php,Laravel,Api,Exception,Exception Handling,在Laravel5.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 alway
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]
}
预期的行为在中是可见的,尽管问题不同
为什么我得到的是上面的400而不是只有信息的401?
.当默认身份验证中间件检查失败时,它会抛出一个
身份验证异常。您可以通过在exception\Handler.php文件中创建一个unauthenticated
函数来更改此异常的处理方式,请参见下面的示例
protected function unauthenticated($request, AuthenticationException $exception) {
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest('login');
}
谢谢我希望我不必那样做。错误被捕获并作为JSON发送,在我的代码中有一个用于设置响应代码的子句。不过它不起作用:P.作为一个侧节点,验证错误和其他异常也随附400,格式如上所述……您现在在哪里设置响应代码?如果此异常是HttpException的一个实例,请在第一个异常处理程序中注意,否?AuthenticationException
不是HttpExceptionYeah的一个实例,我认为它可能不是。这是不是意味着拉威尔不是天生的?