How to handle error catching within a typst document?

My particular use case is inserting images from a list, if they exists, if they don’t exist then do nothing.

#let list = ("A","B","C")

#for v in list [
  // how to catch and ignore error if image do not exist (path is invalid)
  #image("graphic/" + v + ".jpg")
]

I have tried to play around with #assert and #panic but to no avail.

Thanks in advance for the help! It is really appreciated!

1 Like

Hey,
As far as I know, this is not possible.

Maybe you can try this snippet: Try & Catch - Typst Examples Book (please note the “don’t try this at home”)

A solution is to do the verifying yourself or with a script beforehand and pass the valid files via the --input argument to the Typst file (docs: System Functions – Typst Documentation)


I highly recommend to only use assets which are available to you in a Typst project either from yourself or from packages, instead of relying on a try-catch basis. Meaning, if you provide content through a script or similar, name it accordingly and work with the --input parameter provided by the Typst app.

Typst at the end of the day is a type-setting system.

1 Like

Can I add a similar plea, and give a usage case?

I want to be able to print flags. The data is coming from a database that has ISO 3166-1 2-alpha country codes, so

#flag("EU")

works just fine - EU is on the 3166-1 list as a “reserved” code, and is recognised by FLAGADA package.

But

#flag("CQ")

crashes my entire document – CQ is a reserved 3166-1 code, but not recognised by the FLAGADA package.

This means that to successfully automate a database to publication pipeline, I need to either:

– ensure my terrible Python code can pre-vet that country codes on the database are included in the FLAGADA package;

or

– exhort my users to never enter a country code that is not on the FLAGADA package list.

So I’d be very happy to emit Typst code that looks something like this:

#TRY(#flag("CQ")){#figure(image: "no-flag.png")}

Everything would work like magic!

And Typst would be a step closer to being a robust type-setting system :)

Hello @terasa Could you please post a MWE that contains the code that crashed your document?