如何使用fetch()将自定义错误通过rails后端传递到JavaScript前端



我有一个小的NPC生成器(非玩家角色(用于D&D.我已经建立了一个带有Javascript前端的rails API后端,并且能够在用户删除时传递自定义消息来提醒他们。我现在正试图在他们创建一个新的NPC时防止坏数据。我已经验证了我的后端,以便创建新的NPC;名称";。那部分有效,我发出了警报。但是,我传递的自定义JSON消息没有出现。它要么用";未定义的";或者由于名称不存在而出现未捕获的引用错误。

我尝试过使用catch和if response.ok来让它工作,但我无法将自定义错误显示在警报上。

请参阅下面来自控制器的CREATE代码和来自适配器的post请求的fetch((代码。如果需要,还可以链接到我的完整git回购。https://github.com/Santiago548/NPC_Generator

下面是我从控制器创建的带有呈现JSON错误的CREATE,当用户没有输入名称时,我试图将该错误传递给他们。

def create
npc = Npc.new(npc_params)
if npc.save
render json: NpcSerializer.new(npc)
else
render json: {errors: 'NPC could not be created'}
end
end

下面是我的javascript中的fetch((函数,它确实创建了

fetch(this.baseUrl, configNpcRand)
.then(res => res.json())
.then(json => {
let npc = new Npc(json.data.attributes)
npc.attachToDomNpcList() 
})
randomNpcForm.reset()
npcForm.reset()
}

作为第一项措施,表单必须包含验证,以通知用户详细信息不完整,而无需返回POST。参见此处

在后面,关键是要有正确的错误处理。我会尝试以下方法:

def create
npc = Npc.new(npc_params)
if npc.save!
begin
render json: NpcSerializer.new(npc)
rescue ActiveRecord::RecordInvalid => invalid
render json: { error: invalid }, status: :unprocessable_entity
end
end
end

在这里,您尝试save!,这将在记录无效时引发错误。(假设您对模型进行了验证(

在前面,呼叫还需要正确的错误处理

async function postNPC(baseUrl, configNpcRand) {
try {
const response = await fetch(baseUrl, configNpcRand);
if(response.ok){
npcData = await response.json()
return npcData // Don't handle NPC creation here
}
// This  handles the case where the fetch is successful,
// but the server doesn't return status OK, as will happen when
// everything is fine but the NPC params are incomplete.
return { error: 'Please fill in all the NPC details' };
} 
catch(e) {
// This error would handle other errors
// for example, when there is no response from the server
return { error: e };
}  
}

async/await synthax增加了的可读性

最新更新