попробуй поймать шаблон в Laravel - PullRequest
0 голосов
/ 03 мая 2018

Мне было интересно, есть ли способ в 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?

1 Ответ

0 голосов
/ 03 мая 2018

Вы можете поймать и создать свой собственный ответ в методе render на /app/Exceptions/Handler.php:

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

Будьте осторожны, так как этот подход затронет все те же исключения, что и улов

...