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 send the message in different structure ? #103

Closed
issam-seghir opened this issue Mar 7, 2024 · 3 comments
Closed

How to send the message in different structure ? #103

issam-seghir opened this issue Mar 7, 2024 · 3 comments

Comments

@issam-seghir
Copy link

issam-seghir commented Mar 7, 2024

instead of :
if (!foundUser) return next(createError.NotFound("User not found"));

i want to send an object like this :

	if (!foundUser) return next(createError.NotFound(
		{
			field : "email",
			message: "User not found"
		}	
));

// the same as :  res.status(404).json({field:"email", message:"User not found"})
@issam-seghir issam-seghir changed the title How to send the message in deferent structure ? How to send the message in different structure ? Mar 7, 2024
@jonchurch
Copy link
Member

jonchurch commented Mar 8, 2024

Adding custom properties to errors is only supported currently when using createError().

One property you can't set in the object is the status or statusCode, you have to pass it as the first arg.

  const error = 
    createError(404, {
      field: "email",
      message: "User not found"
    })

  console.log(error.name) // NotFoundError
  console.log(error.field) // email
  console.log(error.message) // User not found
  
 const stillNotFound = createError(404, {
     status: 500, // setting status here will be ignored
      field: "email",
      message: "User not found"
    })
console.log(stillNotFound.status) // 404

The shortcut method forms are just constructors that accept a message arg and nothing else. They're used to power the createError interface and allow you to do things like:

    const error = 
    createError(404, {
      field: "email",
      message: "User not found"
    })

  console.log(error instanceof createError.NotFound) // true

@issam-seghir
Copy link
Author

thanks, but i usually prefer using a shortcut method to make my code more readable. For instance, instead of using a status code such as 404, I prefer to use "NotFound".
I was wondering if using "createError(404, {...})" would be the same as "res.status(404).json({...})" in readability or mybe using res object is better .
I think it would be better if I could pass a JSON object using the shortcut method

@jonchurch
Copy link
Member

I think it would be better if I could pass a JSON object using the shortcut method

I agree this is likely what users expect.

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

3 participants