Php 如何在Laravel中更改UnauthorizedHttpException errorHandler auth.basic
我正在尝试在Laravel5.5.48中使用basic auth制作apiPhp 如何在Laravel中更改UnauthorizedHttpException errorHandler auth.basic,php,laravel,api,authentication,Php,Laravel,Api,Authentication,我正在尝试在Laravel5.5.48中使用basic auth制作api 当验证成功时(“用户名”和“密码”)响应正确,但如果验证失败(错误的“用户名”和“密码”数据),则显示错误 我没有尝试,但无法更改响应上的异常显示(response()->json(['status'=>'auth failed'])) routes/api.php Route::post('/index', 'Api\MyController@index')->middleware('auth.basic')
当验证成功时(“用户名”和“密码”)响应正确,但如果验证失败(错误的“用户名”和“密码”数据),则显示错误
我没有尝试,但无法更改响应上的异常显示(response()->json(['status'=>'auth failed'])) routes/api.php
Route::post('/index', 'Api\MyController@index')->middleware('auth.basic');
app/Http/Controllers/Api/MyController@index
public function index(Request $request)
{
return response()->json(array('status' => 'success'));
}
请注意,如果您将
APP_ENV
更改为“production”并且APP_debug=false,那么您得到的错误是为了帮助您在localhost中进行调试而设计的
它不会显示整个错误堆栈
但是,要捕获错误并手动处理,请在App\Exceptions\Handler
公共函数呈现($request,Exception$Exception)
{
if($Symfony\Component\HttpKernel\exception\unauthorizedhttpeexception的异常实例){
return response()->json(['status'=>'auth failed'],401);
}
返回父::render($request,$exception);
}
您可以使用异常处理程序
:
在app/Exceptions/Handler.php中:
公共函数呈现($request,Exception$Exception)
{
if($UnauthorizedException的异常实例){
return response()->json(['status'=>'auth failed'],response::HTTP\u UNAUTHORIZED);
}
返回父::render($request,$exception);
}
不要忘记使用未经授权的异常
和响应
:
使用Symfony\Component\HttpKernel\Exception\unauthorizedhttpeexception
使用Symfony\Component\HttpFoundation\Response
查看有关Laravel异常处理程序的更多详细信息
希望能有帮助