Skip to content

Handle errors ​

Use this when writing the error handling around Formulon calls. Three things can go wrong, and each arrives on its own channel: a call made with the wrong kind of argument, a value the engine refuses, and an Excel error that a formula produces as its result.

Catch a refused call by its code ​

A call the engine refuses throws FormulonError. Its code is a StatusCode number, and enumName(StatusCode, code) gives the member name. message is for display and context holds the details, so match on code, not on the text.

js
import createFormulon, { StatusCode, enumName } from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const attempts = [
    () => wb.sheet('Missing'),
    () => wb.addSheet('sheet1'),
    () => wb.removeSheet(0),
    () => wb.sheet(5),
  ]
  for (const attempt of attempts) {
    try {
      attempt()
    } catch (e) {
      if (!(e instanceof formulon.FormulonError)) throw e
      console.log(enumName(StatusCode, e.code))
    }
  }
} finally {
  wb.dispose()
}
// NotFound
// AlreadyExists
// PreconditionFailed
// SheetIndexOutOfRange
python
import formulon
from formulon import FormulonError, StatusCode, Workbook

with Workbook.create_default() as wb:
    attempts = [
        lambda: wb.sheet("Missing"),
        lambda: wb.add_sheet("sheet1"),
        lambda: wb.remove_sheet(0),
        lambda: wb.sheet(5),
    ]
    for attempt in attempts:
        try:
            attempt()
        except FormulonError as e:
            print(formulon.enum_name(StatusCode, e.code))
# NOT_FOUND
# ALREADY_EXISTS
# PRECONDITION_FAILED
# SHEET_INDEX_OUT_OF_RANGE

A refused call changes nothing in the workbook. Error model lists which status each kind of refusal uses.

Tell a wrong call from a refused value ​

An argument of the wrong type, or a fractional number where an integer belongs, is a programming error and throws before the engine runs: TypeError and RangeError in JavaScript, TypeError in Python. A value of the right type that the engine does not accept, such as a negative row, throws FormulonError with a status code. Both messages read <Class>.<method> <argument> <constraint>.

js
import createFormulon, { StatusCode } from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  const attempts = [
    () => wb.setDate1904('yes'),
    () => ws.insertRows(1.5, 2),
    () => ws.insertRows(-1, 0),
  ]
  for (const attempt of attempts) {
    try {
      attempt()
    } catch (e) {
      const kind = e instanceof formulon.FormulonError ? `FormulonError ${e.code === StatusCode.InvalidArgument}` : e.name
      console.log(kind, '|', e.message)
    }
  }
} finally {
  wb.dispose()
}
// TypeError | Workbook.setDate1904 date1904 must be a boolean
// RangeError | Sheet.insertRows first must be an integer
// FormulonError true | Sheet.insertRows first -1 is outside the grid
python
from formulon import FormulonError, InvalidArgumentError, Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    attempts = [
        lambda: wb.set_date1904(1),
        lambda: ws.insert_rows(1.5, 2),
        lambda: ws.insert_rows(-1, 0),
    ]
    for attempt in attempts:
        try:
            attempt()
        except (TypeError, FormulonError) as e:
            print(type(e).__name__, isinstance(e, InvalidArgumentError), "|", e)
# TypeError False | Workbook.set_date1904 date1904 must be a boolean
# TypeError False | Sheet.insert_rows first must be an integer
# InvalidArgumentError True | [INVALID_ARGUMENT] Sheet.insert_rows first -1 is outside the grid

A boolean argument takes true or false only; no other value is read as truthy. API conventions has the constraint vocabulary and the class each case raises.

Read an Excel error in a cell ​

#DIV/0!, #N/A and the other Excel errors are values, not exceptions. The call that reads them succeeds and returns an ExcelError, whose code is an ErrorCode and whose string form is the text Excel shows. setError stores an error literal, and setValue stores an ExcelError back as it is.

js
import createFormulon, { ErrorCode } from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setFormula('A1', '=1/0')
  ws.setError('A2', ErrorCode.NA)
  ws.setFormula('A3', '=IFERROR(A1,"n/a")')

  const value = ws.getValue('A1')
  console.log(value instanceof formulon.ExcelError, String(value)) // true #DIV/0!
  console.log(value.code === ErrorCode.Div0) // true
  console.log(String(ws.getValue('A2')), ws.getValue('A3')) // #N/A n/a
} finally {
  wb.dispose()
}
python
from formulon import ErrorCode, ExcelError, Workbook

with Workbook.create_default() as wb:
    ws = wb[0]
    ws.set_formula("A1", "=1/0")
    ws.set_error("A2", ErrorCode.NA)
    ws.set_formula("A3", '=IFERROR(A1,"n/a")')

    value = ws["A1"]
    print(isinstance(value, ExcelError), value)  # True #DIV/0!
    print(value.code == ErrorCode.DIV0)  # True
    print(ws["A2"], ws["A3"])  # #N/A n/a
bash
# An Excel error is a result: it prints and the command exits 0
formulon eval '=1/0'

Error model lists every error value and what it means.

Locate a formula syntax error ​

A formula that does not parse is refused like any other value, and the error also says where. In JavaScript e.parseError holds code, start, end, line and column; in Python the exception is FormulaSyntaxError and the same fields are on e.parse_error. start and end are UTF-16 offsets into the text passed in, so they can underline the spot in an editor.

js
import createFormulon, { ParseErrorCode, enumName } from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const text = '=SUM(1,2))'
  try {
    wb.sheet(0).setFormula('A1', text)
  } catch (e) {
    if (!(e instanceof formulon.FormulonError) || !e.parseError) throw e
    const { code, start, end } = e.parseError
    console.log(enumName(ParseErrorCode, code)) // UnexpectedToken
    console.log(text) // =SUM(1,2))
    console.log(' '.repeat(start) + '^'.repeat(end - start)) //          ^
  }
} finally {
  wb.dispose()
}
python
import formulon
from formulon import ParseErrorCode, Workbook

with Workbook.create_default() as wb:
    text = "=SUM(1,2))"
    try:
        wb[0].set_formula("A1", text)
    except formulon.FormulaSyntaxError as e:
        pe = e.parse_error
        print(formulon.enum_name(ParseErrorCode, pe.code))  # UNEXPECTED_TOKEN
        print(text)  # =SUM(1,2))
        print(" " * pe.start + "^" * (pe.end - pe.start))  #          ^
bash
# A formula that does not parse exits 65 and prints the position to stderr
formulon eval '=SUM(1,2))'

Formulas and recalculation shows more parser codes.

Catch Python exceptions by class ​

Python raises a subclass of FormulonError chosen by the status, and each subclass also derives from a builtin exception. NotFoundError is a KeyError, IndexOutOfRangeError an IndexError, and InvalidArgumentError, AlreadyExistsError, FormulaSyntaxError and InvalidFileError are ValueErrors. JavaScript has the single FormulonError class and the same distinctions in code.

js
import createFormulon, { StatusCode } from '@libraz/formulon'

const formulon = await createFormulon()
try {
  formulon.Workbook.load(new Uint8Array([1, 2, 3, 4]))
} catch (e) {
  console.log(e.name, e.code === StatusCode.IoZipCorrupt) // FormulonError true
}
python
from formulon import FormulonError, InvalidFileError, NotFoundError, Workbook

try:
    Workbook.load(b"\x01\x02\x03\x04")
except InvalidFileError as e:
    print(type(e).__name__, isinstance(e, ValueError), e.code.name)  # InvalidFileError True IO_ZIP_CORRUPT

with Workbook.create_default() as wb:
    try:
        wb.sheet("Missing")
    except KeyError as e:
        print(isinstance(e, NotFoundError), isinstance(e, FormulonError))  # True True

A status with no narrower class raises the class of its range, and PreconditionFailed raises FormulonError itself. After close(), every call raises WorkbookClosedError. Python API lists every class.