schoero / swissqrbill

Swiss QR Bill generation in Node.js and browsers
MIT License
156 stars 29 forks source link

Translation of Validation Error Messages #441

Closed marbetschar closed 1 week ago

marbetschar commented 2 weeks ago

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 commented 2 weeks ago

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 commented 2 weeks ago

I agree, having an enum key would be nice!

schoero commented 1 week ago

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 commented 1 week ago

Nice, thank you!!