feat(napi-derive): enhance the error messages in object validator (#2034)

This commit is contained in:
LongYinan 2024-04-10 16:52:23 +08:00 committed by GitHub
parent 67f03a7fd4
commit e274cf7ae6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 23 additions and 3 deletions

View file

@ -511,10 +511,18 @@ impl NapiStruct {
obj_field_setters.push(quote! { obj.set(#field_js_name, #alias_ident)?; });
}
if is_optional_field && !self.use_nullable {
obj_field_getters.push(quote! { let #alias_ident: #ty = obj.get(#field_js_name)?; });
obj_field_getters.push(quote! {
let #alias_ident: #ty = obj.get(#field_js_name).map_err(|mut err| {
err.reason = format!("{} on {}.{}", err.reason, #name_str, #field_js_name);
err
})?;
});
} else {
obj_field_getters.push(quote! {
let #alias_ident: #ty = obj.get(#field_js_name)?.ok_or_else(|| napi::bindgen_prelude::Error::new(
let #alias_ident: #ty = obj.get(#field_js_name).map_err(|mut err| {
err.reason = format!("{} on {}.{}", err.reason, #name_str, #field_js_name);
err
})?.ok_or_else(|| napi::bindgen_prelude::Error::new(
napi::bindgen_prelude::Status::InvalidArg,
format!("Missing field `{}`", #field_js_name),
))?;

View file

@ -528,6 +528,18 @@ test('object', (t) => {
rollup: '^4.0.0',
},
})
t.throws(
() =>
receiveAllOptionalObject({
// @ts-expect-error
name: 1,
}),
{
code: 'StringExpected',
message:
'Failed to convert JavaScript value `Number 1 ` into rust type `String` on AllOptionalObject.name',
},
)
})
test('get str from object', (t) => {
@ -631,7 +643,7 @@ test('should throw if object type is not matched', (t) => {
const err1 = t.throws(() => receiveStrictObject({ name: 1 }))
t.is(
err1?.message,
'Failed to convert JavaScript value `Number 1 ` into rust type `String`',
'Failed to convert JavaScript value `Number 1 ` into rust type `String` on StrictObject.name',
)
// @ts-expect-error
const err2 = t.throws(() => receiveStrictObject({ bar: 1 }))