I have a small NPC generator (non-player character) for D&D. I've set up a rails API backend with a Javascript front end and have been able to pass a custom message to alert my user when they delete. I am now trying to protect from bad data when they create a new NPC. I have validated my backend so that to create a new NPC they need to input a "name". that portion works and I had the alert come up. however, the custom JSON message I passed doesn't come up. it would either alert with "undefined" or an uncaught reference error since the name wasn't present.
I have tried using catch and with an, if response.ok to get it working but just can't wrap my head around getting that custom error to show up on the alert.
see below the code for the CREATE from my controller and the fetch() for my post request from my adapter. as well as a link to my full git repo if needed. https://github.com/Santiago548/NPC_Generator
below is my CREATE from the controller with the render JSON error that I am trying to pass to the user when they do not enter a name.
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
below is my fetch() function from my javascript that does create
fetch(this.baseUrl, configNpcRand)
.then(res => res.json())
.then(json => {
let npc = new Npc(json.data.attributes)
npc.attachToDomNpcList()
})
randomNpcForm.reset()
npcForm.reset()
}
As a first measure, your form must contain validations to inform users that the details are incomplete without requiring to POST to the back. See here
In the back, the key is to have proper error handling. I would try the following:
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
Here, you attempt to save!
which will raise errors when the record is invalid. (assuming you have validations on the model)
In the front, the call also requires proper error handling
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 };
}
}
The async/await synthax increase readability