0
In my system I have the store
, which is responsible for maintaining the status and also sending http requests to the server. An example of this is this method here:
async novoLancamento( valor: string ) {
this.loading.item = true;
try {
const lancamento = new Lancamento();
lancamento.valor = parseFloat( valor );
await this.saveAny(
lancamento,
rotaEvento.lancamento(this.item.id_evento )
);
this.helper.setAlert('Cadastrado');
} catch (e) {
this.helper.setAlert('Erro');
throw e;
} finally {
this.loading.item = false;
}
}
There’s a Button
in my View
who calls this method is does an action case of certain:
<Button
icon="save"
loading={this.store.loading.item}
title="CADASTRAR"
onClick={() => this.store.novoLancamento( this.state.valor )
.then( () => this.setState({ movimentacao: false }))
}
/>
But doing so the compiler keeps showing me this alert:
[Unhandled promise rejection: TypeError: undefined is not an object]
From what I understand it’s because I don’t capture the catch
there at the Buttom. But in my structure there is no need to treat it, what matters to me is only the then
.
So my question is: is my code wrong? I mean, are you breaking any rules?
**Edit A colleague down here said it’s not good practice to relaunch an exception. I went to research on the subject, I found a story on the Mozilla website MDN web Docs that does just that, relaunches an exception.
Relaunching an exception. You can use throw to relaunch an exception after you catch it. The following example takes an exception with a value number and re-launch if the value is greater than 50. The relaunched exception propagates to the Encapsulator function or to the higher level so that the user sees it.
try { throw n; // lança uma exceção com um valor numérico } catch (e) { if (e <= 50) { // instruções para tratar exceções 1-50 } else { // não pode tratar esta exceção então relança throw e; } }
The error doesn’t happen because you don’t use the
catch
. Question https://answall.com/q/58536/99718 has some answers that might help you.– Valdeir Psr
There are other questions that should help even more. This use is quite wrong, maybe async too. Exception was the most poorly used programming language mechanism, that async took first place.
– Maniero
@Maniero thanks for the answer. If possible, put the correct way to do this work.
– Rafael Silva
It depends on the context you don’t have to fix everything. Capturing exception and casting again doesn’t make sense. You can start here: https://answall.com/questions/tagged/exce%C3%A7%C3%a3o? tab=Votes.
– Maniero