getId(); $quantity = $data->getNumber(); $userId = $this->user_id; // 设置默认数量 if ($quantity <= 0) { $quantity = 1; } // 先进行验证,避免不必要的事务开销 $validation = new ItemCraftValidation([ 'user_id' => $userId, 'recipe_id' => $recipeId, 'quantity' => $quantity ]); // 验证数据 $validation->validated(); // 调用合成服务(服务内部会处理事务) $result = CraftService::craftItem($userId, $recipeId, [ 'quantity' => $quantity, 'source_type' => 'app_craft', 'device_info' => request()->userAgent(), 'ip_address' => request()->ip(), ]); if (!$result) { throw new LogicException("合成失败,请检查材料是否充足或配方是否解锁"); } // 设置响应状态 $this->response->setCode(0); $this->response->setMsg('合成成功'); Log::info('用户物品合成成功', [ 'user_id' => $userId, 'recipe_id' => $recipeId, 'quantity' => $quantity, 'result' => $result ]); } catch (\UCore\Exception\ValidateException $e) { // 验证失败 $this->response->setCode(400); $this->response->setMsg($e->getMessage()); Log::warning('物品合成验证失败', [ 'user_id' => $userId ?? null, 'recipe_id' => $recipeId ?? null, 'quantity' => $quantity ?? null, 'error' => $e->getMessage() ]); } catch (LogicException $e) { // 业务逻辑异常 $this->response->setCode(400); $this->response->setMsg($e->getMessage()); Log::warning('用户物品合成失败', [ 'user_id' => $userId ?? null, 'recipe_id' => $recipeId ?? null, 'quantity' => $quantity ?? null, 'error' => $e->getMessage() ]); } catch (\Exception $e) { // 系统异常 $this->response->setCode(500); $this->response->setMsg('系统错误,请稍后再试'); Log::error('物品合成操作异常', [ 'user_id' => $userId ?? null, 'recipe_id' => $recipeId ?? null, 'quantity' => $quantity ?? null, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); } return $response; } }