fastify / fastify/help

Managing custom HTTP errors with statusCode (with examples)?

Open
#782 2 comments 0 reactions 0 assignees View on GitHub
help wanted
Dominant language
No language data
Stars
68
Forks
8
Avg merge
11h 2m
Merged PRs (30d)
2

Description

I know there are many ways how to throw an error message, but, I'm looking for the right one or one which will fit them all. I would like to work with proper HTTP Status Codes and use and send them depending on what happen. The same should work for both WEB and API requests/responses as well.

The simplest would be probably this one. However, I don't like it because it's not a real instance of error.
```JS
app.get('/error', async (req, res) => {
throw { statusCode: 404, message: 'Not Found' };
});
```

Better and most likely best one would be this one. Is an instance of error and everything is working fine. You could even add some additional properties which you can reuse within **setErrorHandler**.
```JS
app.get('/error', async (req, res) => {
const err = new Error();
err.statusCode = 404;
err.message = 'Not found';
throw err;
});
```

Using the code above a lot, makes a lot of work writing it all the time, so I was thinking about some decorator. The only thing, i don't know which part should be decorated and used. The app instance or response. So, there are two examples with usage code...

**App Decorator**
```JS
import http from 'http';

app.decorate('error', function (statusCode, message) {
const error = new Error();
error.statusCode = statusCode;
error.error = http.STATUS_CODES[statusCode];
error.message = message ?? http.STATUS_CODES[statusCode];
throw error;
});

app.get('/error', async (req, res) => {
app.error(404, 'Your Custom Message Here');
});
```

**Response Decorator**
```JS
import http from 'http';

app.decorateReply('error', function (statusCode, message) {
const error = new Error();
error.statusCode = statusCode;
error.error = http.STATUS_CODES[statusCode];
error.message = message ?? http.STATUS_CODES[statusCode];
this.send(error);
});

app.get('/error', async (req, res) => {
res.error(404, 'Your Custom Message Here');
return res;
});
```

I'm thinking that the second one is better just because you're sending a reply and not breaking the whole response with a throw, but I might get wrong.

It would be wonderful If someone could look and give some suggestions about my idea. Thanks a lot!

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.