lukeautry / tsoa

Build OpenAPI-compliant REST APIs using TypeScript and Node
MIT License
3.48k stars 498 forks source link

Handle errors by throwing them #1631

Closed edwinm closed 2 months ago

edwinm commented 4 months ago

Sorting

Feature request

Current situation

The documentation is a bit sparse regarding handling errors.

In have a GET method like this:

public async getAppDetails(@Path() slug: string, @Res() notFoundResponse: TsoaResponse<404, { reason: string }>): Promise<AppDetails | undefined> {

and when an object is not found, I do

return notFoundResponse(404, { reason:No app with slug '${slug}' found});

This is quite verbose.

Improved situation

Why not just throw an error? I know Exceptions are not reflected in TypeScript, so a annotation is still needed, but this looks more clear:

@Throws(404, "Not found");
public async getAppDetails(@Path() slug: string): Promise<AppDetails | undefined> {

and when an object is not found:

throw new TsoaError({code: 404, reason:No app with slug '${slug}' found});

When tsoa catches the error, it creates a Response with a 404 code and the reason.

Reasoning

Especially with multiple possible error codes, having them all as an argument doesn't make the code better.

Also, throwing an error makes it very clear what the intention is.

Other solutions

Maybe tsoa already has better options than the example I provided for the current situation.

In that case, please expand the documentation because I couldn't find much about handling errors.

github-actions[bot] commented 4 months ago

Hello there edwinm 👋

Thank you for opening your very first issue in this project.

We will try to get back to you as soon as we can.👀

WoH commented 3 months ago

You can throw and set an express error handling middleware to catch the error. Note that you have to document the error response format manually on the Endpoint though

github-actions[bot] commented 2 months ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days