| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- <?php
- namespace App\Http\Controllers;
- use App\Constants\HttpStatus;
- use App\Models\Agent\Agent;
- use Closure;
- use Illuminate\Http\JsonResponse;
- use Illuminate\Validation\ValidationException;
- use Illuminate\Database\Eloquent\ModelNotFoundException;
- abstract class AgentApiController extends Controller
- {
- protected function execute(Closure $callback): JsonResponse
- {
- try {
- return $this->success($callback());
- } catch (ValidationException $e) {
- return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
- } catch (ModelNotFoundException $e) {
- return $this->error(HttpStatus::CUSTOM_ERROR, '数据不存在');
- } catch (\PDOException $e) {
- // QueryException inherits PDOException/RuntimeException; never expose SQL or bindings.
- report($e);
- return $this->error(HttpStatus::CUSTOM_ERROR, '系统处理失败,请稍后重试');
- } catch (\InvalidArgumentException | \RuntimeException $e) {
- return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
- } catch (\Throwable $e) {
- report($e);
- return $this->error(HttpStatus::CUSTOM_ERROR, '系统处理失败,请稍后重试');
- }
- }
- /** 下载类接口:成功时直接返回文件响应,出错时和 execute() 一样返回 JSON 错误。 */
- protected function executeFile(Closure $callback): \Symfony\Component\HttpFoundation\Response
- {
- $file = null;
- $error = $this->execute(function () use ($callback, &$file) {
- $file = $callback();
- return null;
- });
- return $file ?? $error;
- }
- protected function currentAgent(): Agent
- {
- $agent = request()->attributes->get('agent');
- if (!$agent instanceof Agent) {
- throw new \RuntimeException('请先登录');
- }
- return $agent;
- }
- }
|