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

Translation of Validation Error Messages #441

Closed
marbetschar opened this issue Aug 25, 2024 · 4 comments · Fixed by #442
Closed

Translation of Validation Error Messages #441

marbetschar opened this issue Aug 25, 2024 · 4 comments · Fixed by #442
Labels
feature request New feature or request

Comments

@marbetschar
Copy link

Is there a way to translate the error messages?

We use SwissQRCode to generate a QR Code based on dynamic formular data - and it would be nice to provide the user with information about which validation failed in their language.

@schoero
Copy link
Owner

schoero commented Aug 25, 2024

There is no built in way to do this.

But the errors are exported and can be caught and re-thrown with a translated message:

import { SwissQRBill } from "swissqrbill/pdf";
import { ValidationError, ValidationErrors } from "swissqrbill/errors";

const TRANSLATED_ERRORS_DE: Record<ValidationErrors, string> = {
  [ValidationErrors.AMOUNT_LENGTH_IS_INVALID]: "Der Betrag darf maximal 12 Ziffern enthalten",
  //...
};

try {
  const qrBill = new SwissQRBill(/* data */);
  //...
} catch(error) {
  if(error instanceof ValidationError){
    throw new Error(TRANSLATED_ERRORS_DE[error.message]);
  }
}

What bothers me with that solution is that the error message currently has to be used for the mapping.

I think the best solution would be to add the enum key as an error.code property to provide a consistent and reliable reference for error handling.

@marbetschar
Copy link
Author

I agree, having an enum key would be nice!

@schoero
Copy link
Owner

schoero commented Sep 1, 2024

This is now implemented in v4.1.0 and can be used like this:

import { SwissQRBill } from "swissqrbill/pdf";
import { ValidationError, ValidationErrors } from "swissqrbill/errors";

const TRANSLATED_ERRORS_DE: Record<ValidationError["code"], string> = {
  AMOUNT_LENGTH_IS_INVALID: "Der Betrag darf maximal 12 Ziffern enthalten",
  //...
};

try {
  const qrBill = new SwissQRBill(/* data */);
  //...
} catch(error) {
  if(error instanceof ValidationError){
    throw new Error(TRANSLATED_ERRORS_DE[error.code]));
  }
}

@marbetschar
Copy link
Author

Nice, thank you!!

@schoero schoero added the feature request New feature or request label Sep 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants