AgentApiController.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Constants\HttpStatus;
  4. use App\Models\Agent\Agent;
  5. use Closure;
  6. use Illuminate\Http\JsonResponse;
  7. use Illuminate\Validation\ValidationException;
  8. use Illuminate\Database\Eloquent\ModelNotFoundException;
  9. abstract class AgentApiController extends Controller
  10. {
  11. protected function execute(Closure $callback): JsonResponse
  12. {
  13. try {
  14. return $this->success($callback());
  15. } catch (ValidationException $e) {
  16. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  17. } catch (ModelNotFoundException $e) {
  18. return $this->error(HttpStatus::CUSTOM_ERROR, '数据不存在');
  19. } catch (\PDOException $e) {
  20. // QueryException inherits PDOException/RuntimeException; never expose SQL or bindings.
  21. report($e);
  22. return $this->error(HttpStatus::CUSTOM_ERROR, '系统处理失败,请稍后重试');
  23. } catch (\InvalidArgumentException | \RuntimeException $e) {
  24. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  25. } catch (\Throwable $e) {
  26. report($e);
  27. return $this->error(HttpStatus::CUSTOM_ERROR, '系统处理失败,请稍后重试');
  28. }
  29. }
  30. protected function currentAgent(): Agent
  31. {
  32. $agent = request()->attributes->get('agent');
  33. if (!$agent instanceof Agent) {
  34. throw new \RuntimeException('请先登录');
  35. }
  36. return $agent;
  37. }
  38. }