API 个异常 Laravel 5
API exceptions in Laravel 5
我想从我的一个控制器(或将来在多个控制器中)捕获所有普通异常(Exception
class 的实例)以统一它们的行为。我知道如何为 Exceptions/Handler.php 中的异常创建全局处理程序,但如何将它们限制为某些特定的控制器?
我想要做的是 return 这样的数组 JSON 格式每当在我的 API 控制器中抛出异常时:
[
'error' => 'Internal error occurred.'
]
我可以决定抛出我自己的异常 class,也许 ApiException
,但我也想处理第三方异常,例如数据库错误。
我应该直接将一些值传递给请求对象吗?如果是这样,如何?或者也许还有其他方法?
你可以这样做:
创建一个例外class
class APIException extends Exception{
}
然后从控制器扔出去
throw new APIException('api exception');
并从 Exceptions/Handler.php
中捕获它
public function render($request, Exception $e)
{
if ($e instanceof APIException){
return response(['success' => false, 'data' => [], 'message' => $e->getMessage(), 401);
}
if ($e instanceof SomeException){
return response(['success' => false, 'data' => [], 'message' => 'Exception'], 401);
}
return parent::render($request, $e);
}
如果要为特定控制器呈现不同类型的异常,可以使用请求对象检查当前控制器:
Exceptions/Handler.php
public function render($request, Exception $e)
{
if($request->route()->getAction()["controller"] == "App\Http\Controllers\ApiController@index"){
return response()->json(["error" => "An internal error occured"]);
}
return parent::render($request, $e);
}
您还可以根据请求的路径模式进行过滤。
转到文件 app\Exceptions\Handler.php
:
public function render($request, \Exception $e)
{
/* Filter the requests made on the API path */
if ($request->is('api/*')) {
return response()->json(["error" => "An internal error occurred"]);
}
return parent::render($request, $e);
}
我想从我的一个控制器(或将来在多个控制器中)捕获所有普通异常(Exception
class 的实例)以统一它们的行为。我知道如何为 Exceptions/Handler.php 中的异常创建全局处理程序,但如何将它们限制为某些特定的控制器?
我想要做的是 return 这样的数组 JSON 格式每当在我的 API 控制器中抛出异常时:
[
'error' => 'Internal error occurred.'
]
我可以决定抛出我自己的异常 class,也许 ApiException
,但我也想处理第三方异常,例如数据库错误。
我应该直接将一些值传递给请求对象吗?如果是这样,如何?或者也许还有其他方法?
你可以这样做:
创建一个例外class
class APIException extends Exception{
}
然后从控制器扔出去
throw new APIException('api exception');
并从 Exceptions/Handler.php
中捕获它public function render($request, Exception $e)
{
if ($e instanceof APIException){
return response(['success' => false, 'data' => [], 'message' => $e->getMessage(), 401);
}
if ($e instanceof SomeException){
return response(['success' => false, 'data' => [], 'message' => 'Exception'], 401);
}
return parent::render($request, $e);
}
如果要为特定控制器呈现不同类型的异常,可以使用请求对象检查当前控制器:
Exceptions/Handler.php
public function render($request, Exception $e)
{
if($request->route()->getAction()["controller"] == "App\Http\Controllers\ApiController@index"){
return response()->json(["error" => "An internal error occured"]);
}
return parent::render($request, $e);
}
您还可以根据请求的路径模式进行过滤。
转到文件 app\Exceptions\Handler.php
:
public function render($request, \Exception $e)
{
/* Filter the requests made on the API path */
if ($request->is('api/*')) {
return response()->json(["error" => "An internal error occurred"]);
}
return parent::render($request, $e);
}