Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to throw 404 error with some custom data fields #1015

Open
engp8691 opened this issue Mar 12, 2024 · 1 comment
Open

How to throw 404 error with some custom data fields #1015

engp8691 opened this issue Mar 12, 2024 · 1 comment

Comments

@engp8691
Copy link

engp8691 commented Mar 12, 2024

I would like to ask gurus here. I has a router which looks for a user. If it does not find the user, it throws a 404 error with a message. That is no problem. But if I want to throw an error as an object. It does not work

{
statusCode: 404,
name: 'LookForUser',
internalCode: 'E610014',
correlationId: '00-905e24caee8691b74be2c3ae6d50178c-d38df853b95a5868-00'
}

If i change the statusCode to 400 or 40x but not 404, it work.

This is my codes

import routes from './constatnt'
import { Schema, schema } from './schema'

server.route<Schema>({
    method: routes.method,
    url: routes.url,
    schema,
    errorHandler: (error, request, reply) => {
      server.errorHandler({ ...error }, request, reply)
    },
    handler: async (request, reply) => {
      try {
        const user = await clients.authService.checkUser(request.body?.userDetails)
        reply.send(user)
      } catch (e) {

      throw ({
      statusCode: 404,
        name: 'LookForUser',
        internalCode: 'E610014',
        correlationId: '00-905e24caee8691b74be2c3ae6d50178c-d38df853b95a5868-00'
      })
      }
    }

Thanks!

Yonglin

      The not found handler is triggered when no route matches, you need to return a 404 manually inside your route if a user cannot be found.

Originally posted by @mcollina in fastify/fastify#402 (comment)

@mcollina
Copy link
Member

You can simply do a reply.code(404).send( { ... })

@mcollina mcollina transferred this issue from fastify/fastify Mar 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants