4

私は Slim3 を使用してかなり大きな JSON API に取り組んでいます。現在、コントローラー/アクションには次のものが散らばっています。

return $response->withJson([
    'status' => 'error',
    'data' => null,
    'message' => 'Username or password was incorrect'
]);

アプリケーションの特定の時点で問題が発生する可能性があり、適切な応答が必要になります。しかし、よくあることの 1 つは、エラー応答が常に同じであることです。はstatus常にerrorであり、dataはオプションであり (フォーム検証エラーの場合dataにはそれらが含まれます) message、ユーザーまたは API の消費者に何が問題なのかを示すように設定されています。

コードの重複のにおいがします。コードの重複を減らすにはどうすればよいですか?

頭のてっぺんから考えられるのは、カスタム例外を作成することだけでした。そのようなApp\Exceptions\AppExceptionものは、オプションを取りdatamessageフォームを取得し$e->getMessage()ます。

<?php

namespace App\Exceptions;

class AppException extends Exception
{
    private $data;

    public function __construct($message, $data = null, $code = 0, $previous = null)
    {
        $this->data = $data;
        parent::__construct($message, $code, $previous);
    }

    public function getData()
    {
        return $this->data;
    }
}

$next次に、try/catch でラップされた呼び出しを行うミドルウェアを作成します。

$app->add(function($request, $response, $next) {

  try {
    return $next($request, $response);
  }
  catch(\App\Exceptions\AppException $e)
  {
    $container->Logger->addCritical('Application Error: ' . $e->getMessage());
    return $response->withJson([
      'status' => 'error',
      'data' => $e->getData(),
      'message' => $e->getMessage()
    ]);
  }
  catch(\Exception $e)
  {
    $container->Logger->addCritical('Unhandled Exception: ' . $e->getMessage());
    $container->SMSService->send(getenv('ADMIN_MOBILE'), "Shit has hit the fan! Run to your computer and check the error logs. Beep. Boop.");
    return $response->withJson([
      'status' => 'error',
      'data' => null,
      'message' => 'It is not possible to perform this action right now'
    ]);
  }
});

これで、コード内のポイントで行う必要があるのは、throw new \App\Exceptions\AppException("Username or password incorrect", null).

これに関する私の唯一の問題は、間違った理由で例外を使用しているように感じ、デバッグが少し難しくなる可能性があることです。

重複を減らし、エラー応答をクリーンアップするための提案はありますか?

4

1 に答える 1