apple / swift-openapi-generator

Generate Swift client and server code from an OpenAPI document.
https://swiftpackageindex.com/apple/swift-openapi-generator/documentation
Apache License 2.0
1.46k stars 122 forks source link

Reduce error handling code between different handlers with similar logic #687

Open Dracks opened 8 hours ago

Dracks commented 8 hours ago

Question

Hello,

I'm using the openapi-generator with Vapor, and I found that I ended generating a lot of code that is identical, because all the responses, no matter the error, are almost identical. I created a discussion in the forum of swift (here: https://forums.swift.org/t/trying-to-reduce-boilercode/76278/17 ) but seems that there is nothing appart of what I did with some macro, that allow you to reduce a huge bunch of this stuff.

Maybe I'm doing it wrong. There is some more elegant way to reduce this?

Thanks, Jaume.

czechboy0 commented 8 hours ago

Hi @Dracks,

this tool generates code for the OpenAPI document. If the OpenAPI document contains a lot of duplicated types, the generated Swift code will contain duplicated types. There isn't much the tool can do.

Could you post your OpenAPI doc? Maybe there are ways to optimize that

Dracks commented 7 hours ago

Hey,

No, for me the problem is not the types, the output for the types is fine. But the return line that I need to do for every "expected" error, is almost identical, but different.

My concern is things like the following: https://github.com/Dracks/mr-scrooge/blob/63dee13da9e3f41d8b918b70877296053d9dee3e/src/swift-server/rules/rule-api-impl.swift#L39-L44

You can see in the same file, I'm doing all the time the same, but since the output type per endpoint is different, I cannot create a function that returns something like "Protocol NotFound" or similar stuff.

You can see my current OpenAPI doc here: https://github.com/Dracks/mr-scrooge/blob/63dee13da9e3f41d8b918b70877296053d9dee3e/src/%40typespec/openapi3/openapi.yaml

czechboy0 commented 7 hours ago

I see, that makes sense. The timing is fortunate here, we recently landed an improved error handling proposal, which would allow you to write convenience functions that validate your input and throw specific errors that get translated to the appropriate response status codes. So you wouldn't need to repeat as much of the error handling in every handler - it's designed to enable the writing of reusable utility functions, which still result in specific error codes.

Can you give that a try and see if it helps?

Dracks commented 7 hours ago

your proposal here is to simply throw an error that implements that protocol, and then catch it on the middleware?

czechboy0 commented 7 hours ago

Yup, exactly.