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

Support empty string messages #134

Closed
wants to merge 2 commits into from
Closed

Conversation

domarp-j
Copy link

@domarp-j domarp-j commented Sep 10, 2024

Checklist

This PR proposes supporting empty strings as messages to support the following use case:

const MyError = createError("MY_CODE", "", 400)
// before -> throws error
// after -> works

throw new MyError() // message = ""
throw new MyError("broken") // message = "broken"

This supports the use case where the user doesn't desire any prefix or suffix to the message; they want the message to match the argument passed to the error.

The trim() I admit is a little problematic, but without it, the above example looks like:

throw new MyError("broken") // message = " broken" (note the space)

index.js Outdated
@@ -27,7 +27,7 @@ function createError (code, message, statusCode = 500, Base = Error) {
this.cause = args.pop().cause
}

this.message = format(message, ...args)
this.message = format(message, ...args).trim()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure which one will be better, most of the time the if clause will be executed.

Suggested change
this.message = format(message, ...args).trim()
if (message) args.unshift(message)
this.message = format(...args)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would:

  1. if (typeof message !== 'string') throw Error('Fastify error message must be defined') (line 11)
  2. if (message === '') { this.message = message } else { this.message = format(message, ...args) }

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@climba03003 I implemented your solution; thank you.

@jsumners I tried your solution, but unfortunately it didn't pass tests.

@Uzlopak
Copy link
Contributor

Uzlopak commented Sep 11, 2024

I dislike the solution.

@domarp-j domarp-j closed this Sep 11, 2024
@domarp-j
Copy link
Author

@Uzlopak I appreciate the useful feedback. Closing and implementing my own solution that addresses our particular use case. Thank you for your assistance.

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

Successfully merging this pull request may close these issues.

4 participants