fune/toolkit/components/uniffi-js/js/UniFFI.sys.mjs
Ben Dean-Kawamura bcea304dfa Bug 1786673 - Additional UniFFI type checking r=markh,skhamis
- Implemented `checkType` on more UniFFI FFIConverters.
- Updated the way we handle locating the errors.
   - The old system was that `checkType` inputted a `name` parameter.  I
     think the idea was that parent types would calculate a name
     parameter for their children.  However, this wasn't great because
     it meant we would need to build the strings up-front and throw
     them away in the vast majority of cases where there was no type
     error.
   - The new system is that we use the `UniFFITypeError` class, which
     has a `prependPath` method.  This gets called by the parent type
     FFIConverter to basically do the same work, but it only needs to
     happen when there's actually an error.
   - I think the resulting error messages are pretty good.  I got this
     when passing a list with garbage data to setLocalTabs: "TypeError:
     remoteTabs[0].title: undefined is not a string"
- Added the `UniFFI.sys.mjs` module, which contains shared, non-generated,
  UniFFI JS code.  This is prep-work for
  https://bugzilla.mozilla.org/show_bug.cgi?id=1804078.

Differential Revision: https://phabricator.services.mozilla.com/D166479
2023-01-17 16:07:40 +00:00

39 lines
1.3 KiB
JavaScript

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// This JS module contains shared functionality for the generated UniFFI JS
// code.
// TypeError for UniFFI calls
//
// This extends TypeError to add support for recording a nice description of
// the item that fails the type check. This is especially useful for invalid
// values nested in objects/arrays/maps, etc.
//
// To accomplish this, the FfiConverter.checkType methods of records, arrays,
// maps, etc. catch UniFFITypeError, call `addItemDescriptionPart()` with a
// string representing the child item, then re-raise the exception. We then
// join all the parts together, in reverse order, to create item description
// strings like `foo.bar[123]["key"]`
export class UniFFITypeError extends TypeError {
constructor(reason) {
super();
this.reason = reason;
this.itemDescriptionParts = [];
}
addItemDescriptionPart(part) {
this.itemDescriptionParts.push(part);
}
itemDescription() {
const itemDescriptionParts = [...this.itemDescriptionParts];
itemDescriptionParts.reverse();
return itemDescriptionParts.join("");
}
get message() {
return `${this.itemDescription()}: ${this.reason}`;
}
}