getLandId(); $userItemId = $data->getItemId(); $userId = $this->user_id; // 先进行验证,避免不必要的事务开销 $validation = new \App\Module\Farm\Validations\DisasterRemovalValidation([ 'user_id' => $userId, 'land_id' => $landId, 'item_id' => $userItemId, 'disaster_type' => DISASTER_TYPE::DROUGHT->value ]); // 验证数据 $validation->validated(); // 验证通过后,开启事务 DB::beginTransaction(); // 执行业务逻辑(不再需要验证) $result = CropService::removeDisasterWithItem( $userId, $landId, $userItemId, DISASTER_TYPE::DROUGHT->value, 'land_watering' ); // 提交事务 DB::commit(); // 设置响应状态 $this->response->setCode(0); $this->response->setMsg($result['message']); } catch (\UCore\Exception\ValidateException $e) { // 验证失败,此时可能还没有开启事务 $this->response->setCode(400); $this->response->setMsg($e->getMessage()); Log::warning('用户浇水验证失败', [ 'user_id' => $this->user_id, 'land_id' => $landId ?? null, 'item_id' => $userItemId ?? null, 'error' => $e->getMessage() ]); } catch (LogicException $e) { // 业务逻辑异常,需要回滚事务 if (DB::transactionLevel() > 0) { DB::rollBack(); } // 设置错误响应 $this->response->setCode(400); $this->response->setMsg($e->getMessage()); Log::warning('用户浇水失败', [ 'user_id' => $this->user_id, 'land_id' => $landId ?? null, 'item_id' => $userItemId ?? null, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); } catch (\Exception $e) { // 系统异常,需要回滚事务 if (DB::transactionLevel() > 0) { DB::rollBack(); } // 设置错误响应 $this->response->setCode(500); $this->response->setMsg('系统错误,请稍后再试'); Log::error('浇水操作异常', [ 'user_id' => $this->user_id, 'land_id' => $landId ?? null, 'item_id' => $userItemId ?? null, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); } return $response; } }