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

Custom error param #1096

Open
tuntag opened this issue Oct 3, 2021 · 2 comments
Open

Custom error param #1096

tuntag opened this issue Oct 3, 2021 · 2 comments

Comments

@tuntag
Copy link

tuntag commented Oct 3, 2021

My project needs to return a custom error format including the error param/key, so please consider to add this feature.

This new additional method could be .withParam() similar to the .withMessage()

Examples

body("name")
  .custom(val => {...check duplicated })
  .withMessage("name is duplicated")

this returns { "name" : "string only" }

Expected

body("name")
  .custom(val => {...check duplicated })
  .withParam("name_exists") // request func
  .withMessage("name is duplicated")

this returns { "name_exists" : "string only" }

@fedeci
Copy link
Member

fedeci commented Oct 3, 2021

I'm not sure of why you would like to change the param name that failed. withMessage accepts an object as a param, so the right place to perform this kind of error response should be there.
e.g.

.withMessage({ reason: "name_esists", message: "name is duplicated" })

@tuntag
Copy link
Author

tuntag commented Oct 4, 2021

Hi, I know this doesn't good practice but you know that we could meet some projects that just need an array of errors key, such as mapping their i18n keys like: for(key in keys) return errors[key]

I have rewrite the result as my needs:

const format = (e: ValidationError): Result<any> => {
    return typeof e.msg === "object"
      ? e.msg
      : e.nestedErrors
        ? e.msg !== "Invalid value(s)"
          ? { require_one: e.msg } // show error message if not default message
          : { require_one: e.nestedErrors.reduce((o, er) => Object.assign(o, this.format(er)), {} as ValidationError) }
        : { [e.param]: e.msg };
}
const result = validationResult(this.req).formatWith(e => format(e));

...but it's not good at all.

Everything would be great if this provides a simple method to change it independently.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants