Skip to Content
NexPDF

Error handling

The nexpdf_sdk::Error enum, the engine's error messages, license error codes, and patterns for reporting failures with NexPDF for Rust.

English

Every NexPDF call returns nexpdf_sdk::Result<T>, which is Result<T, nexpdf_sdk::Error>. There are no status codes to check by hand: the SDK reads the engine's per-thread error and turns it into an Err.

The Error enum

VariantReturned when
Error::Engine(String)An engine call failed. The string is the engine's message ("call failed" if it set none).
Error::License { code, message }license::activate rejected the key. code is the negative status.
Error::Nul(NulError)A string argument contained a NUL byte, which C strings cannot carry.
Error::Io(io::Error)Reading or writing a file failed (Document::open, save, save_linearized_to).
Error::Json(serde_json::Error)With the serde feature: a *_json_value result was not valid JSON.

Error implements std::error::Error and Display (messages start with nexpdf:), and converts from std::io::Error and std::ffi::NulError, so ? works on file reads in a function that returns nexpdf_sdk::Result. The enum is #[non_exhaustive]: a match on it needs a _ arm.

use nexpdf_sdk::{Document, Error};

fn stamp(path: &str) -> nexpdf_sdk::Result<()> {
    let mut doc = Document::open(path)?;
    doc.add_watermark("CONFIDENTIAL")?;
    doc.save("out.pdf")
}

match stamp("upload.pdf") {
    Ok(()) => {}
    Err(Error::Io(e)) => eprintln!("could not read or write the file: {e}"),
    Err(Error::Engine(message)) => eprintln!("NexPDF could not process upload.pdf: {message}"),
    Err(e) => eprintln!("{e}"),
}

How results are checked

The engine reports a failure by returning NULL, an empty buffer or 0 and setting the calling thread's last error. The SDK clears that error before each call and checks it afterwards:

Return typeErr when
Document, StringThe C function returned NULL
Vec<u8>The buffer is empty and the engine set an error (an empty buffer without an error is Ok)
i32The engine set an error, whatever the number. A count of 0 without an error is Ok(0)

So a call that does part of its work and reports the rest as an error is an Err. For example, convert_pdfa_level returning 0 gives Err(Error::Engine(..)) with the list of PDF/A clauses that still fail, while the document keeps the fixes that worked; see PDF/A and PDF/UA validation.

page_width, page_height, trim_memory and memory_usage_bytes return their value directly, and license::is_licensed returns a bool.

Common engine messages

MessageCauseWhat to do
password requiredThe file is encrypted and no password was givenAsk for the password and pass it to Document::open_with_password
incorrect passwordThe password matches neither the user nor the owner passwordAsk again
no license activated: '<module>' requires a NexPDF license keyThe call needs a module and no key is activeCall license::activate at start-up; see Running without a key
the active license does not include the '<module>' moduleYour plan does not include the moduleCheck license::is_licensed(module), or upgrade the plan
internal error: ...The engine caught an unexpected failure on this inputThe process keeps running; report the file to support

Other messages describe the input: a malformed or truncated PDF, a page index out of range, invalid JSON options. They are meant to be logged as they are.

match Document::open_with_password("locked.pdf", "s3cret") {
    Ok(doc) => println!("{} pages", doc.page_count()?),
    Err(Error::Engine(m)) if m == "password required" || m == "incorrect password" => ask_again(),
    Err(e) => return Err(e),
}

License error codes

Error::License { code, .. } holds one of:

CodeMeaning
-1Malformed key
-2Bad signature (the key was changed, or it is not a NexPDF key)
-3Unsupported key version (update the SDK)
-4Expired
-5Not yet valid (check the system clock)
-6Wrong platform
-7Wrong application id

A rejected key leaves the previous license state as it was, so a process that had no key stays in view-only mode.

The last error

nexpdf_sdk::last_error() returns the engine's last error message for the current thread, or None. You rarely need it, because every Err already carries that message, but it is useful when you call nexpdf_sdk::invoke or the raw functions of nexpdf_sdk::sys directly. Every call of the SDK clears the last error first, so a failure never leaks into the next call.

Untrusted input

The engine is written in Rust and fuzzed; a malformed PDF produces an Err, not a crash. When you process uploads:

  • handle the Err per file, so one bad file does not stop a batch;
  • limit the file size you accept before opening it, since documents are read into memory;
  • keep documents in a narrow scope so they are dropped, and their memory freed, on failure too.
fn page_count_or_none(data: &[u8]) -> Option<i32> {
    nexpdf_sdk::Document::from_bytes(data).and_then(|doc| doc.page_count()).ok()
}

On this page