feat(napi-derive): enhance the error messages in object validator (#2034)
This commit is contained in:
parent
67f03a7fd4
commit
e274cf7ae6
2 changed files with 23 additions and 3 deletions
|
@ -511,10 +511,18 @@ impl NapiStruct {
|
||||||
obj_field_setters.push(quote! { obj.set(#field_js_name, #alias_ident)?; });
|
obj_field_setters.push(quote! { obj.set(#field_js_name, #alias_ident)?; });
|
||||||
}
|
}
|
||||||
if is_optional_field && !self.use_nullable {
|
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 {
|
} else {
|
||||||
obj_field_getters.push(quote! {
|
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,
|
napi::bindgen_prelude::Status::InvalidArg,
|
||||||
format!("Missing field `{}`", #field_js_name),
|
format!("Missing field `{}`", #field_js_name),
|
||||||
))?;
|
))?;
|
||||||
|
|
|
@ -528,6 +528,18 @@ test('object', (t) => {
|
||||||
rollup: '^4.0.0',
|
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) => {
|
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 }))
|
const err1 = t.throws(() => receiveStrictObject({ name: 1 }))
|
||||||
t.is(
|
t.is(
|
||||||
err1?.message,
|
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
|
// @ts-expect-error
|
||||||
const err2 = t.throws(() => receiveStrictObject({ bar: 1 }))
|
const err2 = t.throws(() => receiveStrictObject({ bar: 1 }))
|
||||||
|
|
Loading…
Reference in a new issue