fix: 题库生成功能全面修复 - create方法templateId传参、异常改为BadRequest、前端错误消息透传

This commit is contained in:
Developer
2026-05-15 09:55:03 +08:00
parent 186423d172
commit b70dc68a85
2 changed files with 21 additions and 10 deletions
@@ -2,6 +2,7 @@ import {
Injectable,
NotFoundException,
ForbiddenException,
BadRequestException,
Logger,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
@@ -87,15 +88,20 @@ export class QuestionBankService {
tenantId: string | null,
): Promise<QuestionBank> {
if (!createDto.name || !createDto.name.trim()) {
throw new Error('Question bank name is required');
throw new BadRequestException('Question bank name is required');
}
const bank = this.bankRepository.create({
...createDto,
const bankData: any = {
name: createDto.name,
description: createDto.description || '',
createdBy: userId,
tenantId: tenantId || null,
status: QuestionBankStatus.DRAFT,
});
return this.bankRepository.save(bank);
};
if (createDto.templateId) {
bankData.template = { id: createDto.templateId };
}
const bank = this.bankRepository.create(bankData as any);
return this.bankRepository.save(bank as unknown as QuestionBank);
}
async findAll(
@@ -211,7 +217,7 @@ export class QuestionBankService {
createDto: CreateQuestionBankItemDto,
): Promise<QuestionBankItem> {
if (!createDto.questionText || !createDto.questionText.trim()) {
throw new Error('Question text is required');
throw new BadRequestException('Question text is required');
}
await this.findOne(bankId);
const item = this.itemRepository.create({
@@ -261,11 +267,11 @@ export class QuestionBankService {
const bank = await this.findOne(bankId);
if (count <= 0 || count > 50) {
throw new Error('生成数量必须在 1-50 之间');
throw new BadRequestException('生成数量必须在 1-50 之间');
}
if (!knowledgeBaseContent || knowledgeBaseContent.trim().length < 10) {
throw new Error('知识库内容太短,无法生成有效题目');
throw new BadRequestException('知识库内容太短,无法生成有效题目');
}
this.logger.log(`[generateQuestions] Starting AI generation for bank ${bankId}, count: ${count}`);
@@ -316,7 +322,7 @@ export class QuestionBankService {
let parsedQuestions = safeParseJson<any>(response.content as string);
if (!parsedQuestions) {
this.logger.error('[generateQuestions] Failed to parse JSON from AI response');
throw new Error('Invalid JSON format from AI');
throw new BadRequestException('Invalid JSON format from AI');
}
if (!Array.isArray(parsedQuestions)) {
+6 -1
View File
@@ -146,7 +146,12 @@ export const questionBankService = {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ count, knowledgeBaseContent }),
});
if (!response.ok) throw new Error('Failed to generate questions');
if (!response.ok) {
const errBody = await response.text().catch(() => '');
let msg = 'Failed to generate questions';
try { const parsed = JSON.parse(errBody); if (parsed.message) msg = parsed.message; } catch {}
throw new Error(msg);
}
return await response.json();
},