Error handling
How NexPDF for Android reports failures - the exceptions of NexPdfDocument, the return values and lastError of NexPdfJni, license codes, engine messages and untrusted files.
NexPDF for Android reports failures in two ways:
NexPdfDocumentthrows when a document cannot be opened or is used afterclose().NexPdfJnimethods never throw. A failure returns a failure value, andNexPdfJni.lastError()gives the engine's reason on the same thread.
Exceptions
| Exception | Thrown when |
|---|---|
IllegalArgumentException | NexPdfDocument.openBytes, openEbook, openImage, openOffice, fromHtml, fromDocxTemplate or fromHtmlTemplate could not open or create the document. The message is the engine's error; NexPdfDocument.isPasswordError(e) is true for password required and incorrect password |
IllegalStateException | handle() (and so every method of NexPdfDocument) was called after close(): document is closed |
UnsatisfiedLinkError | The first use of NexPdfJni could not load libnexpdf_jni.so or libnexpdf_ffi.so, for example on an ABI the AAR does not include. Later uses throw NoClassDefFoundError |
import com.nexdevit.nexpdf.NexPdfDocument
import com.nexdevit.nexpdf.NexPdfJni
try {
NexPdfDocument.openBytes(upload).use { doc ->
if (!NexPdfJni.addWatermark(doc.handle(), "CONFIDENTIAL")) {
Log.w("NexPDF", "watermark failed: ${NexPdfJni.lastError()}")
return
}
out.writeBytes(doc.saveBytes())
}
} catch (e: IllegalArgumentException) {
Log.w("NexPDF", "NexPDF could not open the upload: ${e.message}")
}Return values of NexPdfJni
| Return type | Failure value |
|---|---|
boolean (actions such as rotatePage, fillFormField) | false |
int counts (such as flattenForms, redactMatches, insertImagePages) | -1 |
long handles (openBytes, openBytesWithPassword, extractPages, openOffice) | 0 |
String (JSON and text) | "" |
byte[] (PNG, PDF, Office files) | an empty array |
Read NexPdfJni.lastError() right after a call that returned a failure value, on the same thread.
Errors are tracked per thread, and a successful call does not always clear the previous error, so
an error message alone does not mean the last call failed. An empty string or array can also be a
real result, for example the text of a scanned page with no text layer.
val png = NexPdfJni.renderPagePng(h, 0, 144.0)
if (png.isEmpty()) error("render failed: ${NexPdfJni.lastError()}")Two rules protect the process, because handles are native pointers:
- Never use a handle after
NexPdfJni.free(handle)ordoc.close().NexPdfDocumentchecks this and throws; a rawlonghandle does not. - Pass
nullonly where a method says it accepts it (for example the values ofsetMetadataor the pages ofremovePageBackground). Some methods hand their arguments straight to native code.
Common engine messages
| Message | Cause | What to do |
|---|---|---|
password required | The file is encrypted and no password was given | Ask for the password and open with NexPdfJni.openBytesWithPassword |
incorrect password | The password matches neither the user nor the owner password | Ask again |
no license activated: '<module>' requires a NexPDF license key | The call needs a module and no key is active | Call NexPdfLicense.initialize in Application.onCreate(); see Running without a key |
the active license does not include the '<module>' module | Your plan does not include the module | Check the key's modules, or upgrade the plan |
internal error: ... | The engine caught an unexpected failure on this input | The app 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, not shown to users word for word.
License codes
NexPdfLicense.initialize (and NexPdfJni.licenseActivate) return 2 for a commercial key, 1
for a trial key, or one of:
| Code | Meaning |
|---|---|
| -1 | Malformed key |
| -2 | Bad signature (the key was changed, or it is not a NexPDF key) |
| -3 | Unsupported key version (update the SDK) |
| -4 | Expired |
| -5 | Not yet valid (check the device clock) |
| -6 | Wrong platform (the key is not for android) |
| -7 | Wrong application id (the package name) |
| -8 | No key in the manifest or the assets (initialize(context) only) |
A rejected key leaves the previous license state as it was, so an app that had no key stays in view-only mode, and an app that had a valid key keeps it.
invoke errors
NexPdfJni.invoke never throws either. It returns
{"ok":false,"error":"..."} with the same messages; the NexPdfInvoke.call helper turns that into
an IllegalStateException.
Untrusted input
The engine is written in Rust and fuzzed; a malformed PDF produces a failure value or an
IllegalArgumentException, it does not crash the app. When you open files from other apps, a
content: URI or a server:
- check every return value, and catch
IllegalArgumentExceptionper file, so one bad file does not stop a batch; - check the file size before opening it, since the whole file is read into memory;
- open and process files off the main thread (see Platform notes);
- close documents with
use { }or try-with-resources so native memory is freed on failure too.
fun pageCountOrNull(bytes: ByteArray): Int? = try {
NexPdfDocument.openBytes(bytes).use { it.pageCount() }
} catch (e: IllegalArgumentException) {
null
}