Php Laravel 5中的API异常

Php Laravel 5中的API异常,php,exception,laravel,exception-handling,laravel-5,Php,Exception,Laravel,Exception Handling,Laravel 5,我想从我的一个控制器(或者将来在几个控制器中)捕获所有普通异常(异常Exceptionclass的实例),以统一它们的行为。我知道如何在exceptions/Handler.php中为异常生成全局处理程序,但如何将它们限制到某个特定的控制器 我想做的是,每当在我的API控制器中引发异常时,以JSON格式返回这样一个数组: [ 'error' => 'Internal error occurred.' ] 我可以决定抛出自己的异常类,可能是ApiException,但我也希望服务于

我想从我的一个控制器(或者将来在几个控制器中)捕获所有普通异常(异常
Exception
class的实例),以统一它们的行为。我知道如何在exceptions/Handler.php中为异常生成全局处理程序,但如何将它们限制到某个特定的控制器

我想做的是,每当在我的API控制器中引发异常时,以JSON格式返回这样一个数组:

[
    'error' => 'Internal error occurred.'
]
我可以决定抛出自己的异常类,可能是
ApiException
,但我也希望服务于第三方异常,例如数据库错误

我应该直接向请求对象传递一些值吗?如果是,怎么做?或者有其他方法吗?

您可以这样做:

创建一个异常类

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);
}

如果要为特定控制器呈现不同类型的异常,可以使用请求对象检查当前控制器:

异常/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);
}
谢谢<代码>$request->route()就是这个问题,但我通过使用
解决了它,如果($request->ajax())
,调试就更容易了。:)