As a backend developer i’ve just lately been immersed in NestJS at my firm. One of many options that captivated me was the power to throw exceptions like throw new AppBadRequest()
to deal with HTTP messages. Having the ability to break the entire http request and returning the http message mid code is gorgeous
Nonetheless, when coding in golang once more i’ve been lacking this factor, i dont know if already exists such a framework however i’ve construct my very own, following this pattern venture: GitHub – dalton02/Qiwi-Base-Backend: Estrutura base para serviços backend utilizando framework Qiwi e Prisma
It really has a college venture of a weblog that i’m engaged on, the framework has a json validator utilizing the reflector, and has some cool stuff, like customized protected and public routes for jwt.
Later i’m considering of expeding this to being extra customizable, and it might be cool for those who guys give me some suggestions, the entire framework is within the “requester” folder.
Instance Implementation
func InsertPost(db *sql.DB, postagem postagensDto.NovaPostagem, response http.ResponseWriter) int {
var lastInsertID int
err := db.QueryRow("INSERT INTO postagem (tipo, titulo, conteudo, usuario_id, tags) VALUES ($1, $2, $3, $4, $5) RETURNING id",
postagem.Tipo, postagem.Titulo, postagem.Conteudo, postagem.UsuarioId, pq.Array(postagem.Tags)).Scan(&lastInsertID)
if err != nil {
httpkit.AppConflict("A battle has occurred: "+err.Error(), response)
// If this perform is known as in excessive order features, the panic will go all the way in which again to the unique http.handleFunc
}
return int(lastInsertID)
}`
Comparability with NestJS
import { Injectable, ConflictException } from '@nestjs/widespread';
@Injectable()
export class PostService {
async insertPost(postagem: NovaPostagem): Promise<quantity> {
attempt {
const end result = await this.postRepository.insert(postagem);
return end result.identifiers[0].id; // Returning the ID of the final put up
} catch (error) {
throw new ConflictException('A battle has occurred: ' + error.message);
}
}
}`
Obs: Sorry if some issues are in portuguese within the codebase
There was some dialogue about this just lately so I’m not going to re-hash it, however on the whole, don’t panic. Try the responses on this thread for more information:
As he mentioned, and as has been mentioned just lately, Golang’s error dealing with is fascinating, and also you’ll like it for those who get used to this fashion of code.
I imply, I actually love the way in which Go handles errors. I’ve been utilizing a number of the Go syntax in TypeScript as properly, and I do know you guys hate utilizing panic, however I’ve examined each edge case and made some 10,000 requests per second to see if it might influence efficiency. I simply suppose this method I take particularly for sending HTTP messages is form of good. I solely use this method to ship early messages to the consumer. In case you see the struct I made, each panic is being recovered and logged. I don’t even imply it’s higher than the unique manner; I’m simply exhibiting a cool various that makes the code clear and form of brief in some methods.
It doesn’t make something clear in any respect. So that you simply panic and get well some place else inside your library? As a result of all I see is lots of complicated exported features (not even strategies) which as an alternative of merely return an error panic. This doesn’t appear good, it feels incorrect, simply incorrect. When somebody says he examined edge circumstances meaning there are nonetheless 100500 methods of breaking every little thing.
This one really appears to be like like recreation of attempt/catch in golang which works straight towards one of many core issues, errors as values. If I wish to throw an exception I code in python. In spite of everything this years with go, I wish to write err != nil and get this err because the final return worth from a perform.
Clearly, we are able to’t cease a developer from doing silly issues. As I noticed, golang’s design is so easy and charming that it makes some individuals suppose unusual issues.
After they suppose greatest practices are incorrect, they don’t suppose their considering is incorrect except they encounter dangerous penalties.
panic is simply caught in defer and executes some logic, which causes leaks when writing code that panic however isn’t caught.
It’s a lot better to let the caller know that an err will happen, slightly than panic implicitly.
1 Like
I believe “silly” is impolite and too robust of a phrase right here. I’m onboard with it not being idiomatic, and I like how Go treats errors as values. However there are lots of frameworks/languages/language designers on the market preferring different paradigms. I don’t suppose it’s nice to shoehorn these into Go per se (like how we deal with errors as values is without doubt one of the issues that makes the language totally different!) however attempt to not be impolite to new neighborhood members.
I imply sorry for those who fell like that is stupity? This works on my companys venture that i’m growing and was very idiomatic to me, i simply needed to share to see if somebody like this method dude, chill…