guigrpa / docx-templates

Template-based docx report creation
MIT License
883 stars 145 forks source link

Detecting error type in customer error handler #313

Closed rbeeler-ha closed 1 year ago

rbeeler-ha commented 1 year ago

Does anyone have an example of using a custom error handler to specifically catch/handle a NullishCommandResultError exception? I'm able to use a custom error handler and rejectNullish=true to intercept null/undefined values, though I'd like to limit that logic to exceptions of that type. Here's what I'm currently using:

errorHandler: (err, command_code) => {
  if (err.message.includes("undefined")) return "";
  else return err;
},

If I look at the values returned with the exception I see:

err.name: "Error" err.message: "TypeError: Cannot read properties of undefined (reading 'primary')" err.stack: call stack

command_code: command that caused the error

So nothing there that tells me the type of error. From the docs:

Using a custom errorHandler in combination with rejectNullish = true allows users to intelligently replace the result of commands that returned null or undefined (make sure to check for NullishCommandResultError).

How do I check for NullishCommandResultError?

jjhbw commented 1 year ago

Have you tried instanceof NullishCommandResultError ?

import createReport, { NullishCommandResultError } from 'docx-templates'

createReport({
    errorHandler: (e, a) => {
        if (e instanceof NullishCommandResultError) {
            console.log('Found!')
        }
    }
})
rbeeler-ha commented 1 year ago

Yep - tried that and it did not work for me. Thanks for the suggestion.

jjhbw commented 1 year ago

Which build toolchain are you using? IIRC instanceof equivalence checking can be tricky with some minifiers.

If instanceof does not work for you, maybe you can check for the presence of the substring is null or undefined and rejectNullish is set in the error's message.

jjhbw commented 1 year ago

The instanceof approach Works On My ~Machine~ Project :tm:, so I'm assuming this is something with your toolchain. Let me know if I'm wrong. Just @ me if you want to discuss this further, or if you have some new insights.