AgentApiController.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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 (\InvalidArgumentException | \RuntimeException $e) {
  20. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  21. } catch (\Throwable $e) {
  22. report($e);
  23. return $this->error(HttpStatus::CUSTOM_ERROR, '系统处理失败,请稍后重试');
  24. }
  25. }
  26. protected function currentAgent(): Agent
  27. {
  28. $agent = request()->attributes->get('agent');
  29. if (!$agent instanceof Agent) {
  30. throw new \RuntimeException('请先登录');
  31. }
  32. return $agent;
  33. }
  34. }