AgentApiController.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. /** 下载类接口:成功时直接返回文件响应,出错时和 execute() 一样返回 JSON 错误。 */
  31. protected function executeFile(Closure $callback): \Symfony\Component\HttpFoundation\Response
  32. {
  33. $file = null;
  34. $error = $this->execute(function () use ($callback, &$file) {
  35. $file = $callback();
  36. return null;
  37. });
  38. return $file ?? $error;
  39. }
  40. protected function currentAgent(): Agent
  41. {
  42. $agent = request()->attributes->get('agent');
  43. if (!$agent instanceof Agent) {
  44. throw new \RuntimeException('请先登录');
  45. }
  46. return $agent;
  47. }
  48. }