【问题标题】:API exceptions in Laravel 5Laravel 5 中的 API 异常
【发布时间】:2015-07-05 16:59:31
【问题描述】:

我想从我的一个控制器(或将来在多个控制器中)捕获所有普通异常(Exception 类的实例)以统一它们的行为。我知道如何在 Exceptions/Handler.php 中为异常创建全局处理程序,但是如何将它们限制为某个特定的控制器?

我想要做的是在我的 API 控制器中抛出异常时以 JSON 格式返回这样一个数组:

[
    'error' => 'Internal error occurred.'
]

我可以决定抛出我自己的异常类,也许是ApiException,但我也想处理第三方异常,例如数据库错误。

我应该直接将一些值传递给请求对象吗?如果是这样,怎么做?或者也许还有其他方法?

【问题讨论】:

    标签: php exception laravel exception-handling laravel-5


    【解决方案1】:

    你可以这样做:

    创建一个异常类

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

    【讨论】:

      【解决方案2】:

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

      异常/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);
      }
      

      【讨论】:

      • 谢谢! $request->route() 是问题,但我使用if ($request->ajax()) 解决了它,调试起来更容易。 :)
      【解决方案3】:

      您还可以按路径模式过滤请求。

      转到文件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);
      }
      

      【讨论】:

        猜你喜欢
        • 2019-06-19
        • 1970-01-01
        • 1970-01-01
        • 2016-03-17
        • 1970-01-01
        • 2016-06-02
        • 2015-09-15
        • 2017-02-23
        • 2015-02-18
        相关资源
        最近更新 更多