【问题标题】:try-catch boilerplate in LaravelLaravel 中的 try-catch 样板
【发布时间】:2018-05-03 14:38:06
【问题描述】:

我想知道 Laravel / PHP 中是否有办法减少 try-catch 逻辑。例如,我的控制器中有两种方法:

存储方法

public function store(Request $request){
    try {

      $order = Order::create($request);

    } catch(\Exception $e) {

     return response()->json([
       "message" => 'An error has occured',
       "error" => $e->getMessage(),
     ], 500);

   }
}

更新方法

public function update(Request $request){
    try {

      $order = Order::update($request);

    } catch(\Exception $e) {

      return response()->json([
        "message" => 'An error has occured',
        "error" => $e->getMessage(),
      ], 500);

    }
 }

正如我们所见,try-catch 在两种情况下都是相同的,返回相同格式的错误。

有没有办法提取此逻辑并将所有控制器方法包装在同一个 try-catch 块中?

【问题讨论】:

  • 你可以通过一个函数来路由它,该函数有一个标志变量传递给它,它选择要运行的内容。
  • 制作异常响应方法?

标签: php laravel exception exception-handling try-catch


【解决方案1】:

您可以在/app/Exceptions/Handler.phprender 方法中捕获并创建自己的响应:

public function render($request, Exception $exception)
{
    if ($exception instanceof \Exception) {
        return response()->json([
          "message" => 'An error has occured',
          "error" => $exception->getMessage(),
        ], 500);
    }

    // or you might want to catch ModelNotFoundException
    // and give same response for all case
    else if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
        return response()->json([
          "message" => 'No model found. Please using valid ID',
          "error" => $exception->getMessage(),
        ], 404);
    }

    return parent::render($request, $exception);
}

小心,因为这种方法会影响所有被捕获的异常

【讨论】:

  • 完美!我可以构建一个自定义异常类来针对较小范围的异常。
  • 欢迎朋友。 :)
猜你喜欢
  • 2014-11-27
  • 2011-05-26
  • 2019-08-06
  • 2014-08-10
  • 2014-05-19
  • 1970-01-01
  • 2013-08-25
  • 2019-06-27
  • 1970-01-01
相关资源
最近更新 更多