Parsley Config Error Messages - parsley.js

I'm trying to override the default error messages using windows.ParsleyConfig, but I have yet to find the correct syntax:
window.ParsleyConfig = {
messages: {
defaultMessage: "This value seems to be invalid.",
type: {
number: "asdasd."
}
}
};
I've tried a few variations of this, non of which has worked. The code is being called before parsley.min.js is loaded.

You need to modify ParsleyConfig.i18n.en (assuming you're using the default locale 'en'), not ParsleyConfig.messages.
// After Parsley has loaded:
window.ParsleyConfig.i18n.en.type.number = "hello";
Alternatively, for most error messages, you can specify them in options:
<form data-parsley-required-message="Hey, fill this in!">

Related

Get require() message error from a smart contract in Ethereum

I'm starting to learn Solidity and how to interact with smart contracts within a Dapp, and I would like to know how can I log/handle errors from the contract in my Dapp.
For example, in the Dapp I have a button, when you click it, it runs a function in the contract, I have a require() there with a specific message: "Wait 15m", basically, the user can only click this button once every 15 minutes.
The button interaction is fired in a try/catch, if the user already clicked the button, so the next time will catch the error. My problem is the error that I'm getting in the console (to debug), it is like:
Error: transaction failed (transactionHash="0xe95c970115f5fe55202d04c2e0cd83c2ff67d3653f5397d7739764d685249da6", transaction={"hash":"0xe95c970115f5fe55202d04c2e0cd83c2ff67d3653f5397d7739764d685249da6","type":2,"accessList":null,"blockHash":null,"blockNumber":null,"transactionIndex":null,"confirmations":0,"from":"0xc6682cDC60a1e4603D051e48A2970E4859C62521","gasPrice":{"type":"BigNumber","hex":"0x59682f11"},"maxPriorityFeePerGas":{"type":"BigNumber","hex":"0x59682f00"}......
It is just a string with this bunch of code, without the error message specified in the require() which is the thing that is firing the error. This is the transaction in Rinkeby.
So, I imagine, in the future, I could have many functions in my contract with many require() with different messages. How can I handle these errors and show valuable information to the user in the UI? Is there any function that could help to get the proper messages?
I'm using:
Ethers - React
Thanks in advance for any help!
To extract error message from revert and require in the contract, please use provider.call to retrieve the error data. The following code works well with alchemy provider and goerli net. (ethers.js version 5.6.8)
const alchemyProvider = new ethers.providers.AlchemyProvider(
(network = "goerli"),
API_KEY
)
const tx = await alchemyProvider.getTransaction("0x5479d838aa66169470a61a8347727b75264e1d5d68d6749e5bd59b44d525dc21");
const code = await alchemyProvider.call(
{
to: tx.to,
from: tx.from,
nonce: tx.nonce,
gasLimit: tx.gasLimit,
gasPrice: tx.gasPrice,
data: tx.data,
value: tx.value,
chainId: tx.chainId,
type: tx.type ?? undefined,
accessList: tx.accessList,
},
tx.blockNumber,
)
const decodedError = SimpleAuction.interface.parseError(code)
console.log(decodedError)
console.log(`Transaction failed: ${decodedError.name}`)
The transaction info in etherscan which error encountered during contract revert execution. So the "code" is detailed and raw error info, and can be parsed and fromatted by interface. The output of error showed in the following.
ErrorDescription {
args: [
BigNumber { _hex: '0x01', _isBigNumber: true },
highestBid: BigNumber { _hex: '0x01', _isBigNumber: true }
],
errorFragment: {
type: 'error',
name: 'BidNotHighEnough',
inputs: [ [ParamType] ],
_isFragment: true,
constructor: [Function: ErrorFragment] {
from: [Function (anonymous)],
fromObject: [Function (anonymous)],
fromString: [Function (anonymous)],
isErrorFragment: [Function (anonymous)]
},
format: [Function (anonymous)]
},
name: 'BidNotHighEnough',
signature: 'BidNotHighEnough(uint256)',
sighash: '0x4e12c1bb'
}
The "BidNotHighEnough" is an reverted error defined in the contract. So that all the detailed erro info.

Field 'name' on type 'RemoteDependencyData' is too long

I've just added Application Insights to my React application. When it attempts to contact the Application Insights server to notify it about Google Adverts loading, I get a 400 error which says: "Field 'name' on type 'RemoteDependencyData' is too long"
I've looked through the config for ApplicationInsights and don't find a way to shorten the name or to ignore certain fetches.
Here is my configuration of the plugin:
initialize(reactPluginConfig) {
const instrumentationKey = publicRuntimeConfig.AppInsights.InstrumentKey
this.appInsights = new ApplicationInsights({
config: {
instrumentationKey,
maxBatchInterval: 0,
disableFetchTracking: false,
extensions: [this.reactPlugin],
extensionConfig: {
[this.reactPlugin.identifier]: reactPluginConfig
}
}
})
this.appInsights.loadAppInsights()
}
Here's the kind of value I'm seeing being passed:
name: "GET https://securepubads.g.doubleclick.net/gampad/ads?gdfp_req=1&pvsid=3899864230170460&correlator=1176166438184394&output=json_html&callback=googletag.impl.pubads.callbackProxy3&impl=fifs&adsid=AGt39rSWeAHAYcWHd55Pv2v0Hn4qiAL6Sl5QTuM8A7Vy0061-z2dWmbQdMXwo-8N5G4e1e5VaGTTm0lLSoER&jar=2019-6-18-23&json_a=1&eid=21063203%2C21063317%2C22316438&vrg=2019061301&guci=2.2.0.0.2.2.0.0&plat=1%3A32776%2C2%3A32776%2C8%3A32776&sc=0&sfv=1-0-33&ecs=20190618&iu_parts=12671339%2Caa_sbdept_bottom_728x90&enc_prev_ius=0%2F1&prev_iu_szs=728x90&prev_scp=department%3Dbody-armor%26category%3DBody%2520Armor%2520%2526%2520Protection&cookie_enabled=1&bc=31&abxe=1&lmt=1560900694&dt=1560900694440&dlt=1560900618064&idt=11742&frm=20&biw=2543&bih=400&oid=3&adxs=1244&adys=2379&adks=1434505235&ucis=d&ifi=9&u_tz=-420&u_his=4&u_h=1440&u_w=2560&u_ah=1440&u_aw=2560&u_cd=24&u_nplug=3&u_nmime=4&u_sd=1&flash=0&url=http%3A%2F%2Flocalhost%3A3000%2Fdepartment%2F10A56330.aspx&dssz=15&icsg=48955391&std=20&vis=2&dmc=8&scr_x=0&scr_y=0&psz=728x90&msz=728x90&blev=0.98&bisch=1&ga_vid=1753854358.1560900630&ga_sid=1560900630&ga_hid=551901891&fws=0"
You can add this telemetry initializer below your call to loadAppInsights to modify your telemetry items on the fly. In this case, it will truncate the RemoteDependencyData name field.
appInsights.addTelemetryInitializer(item => {
if (item.baseType === 'RemoteDependencyData') {
if (item.baseData.name.length > 1024) {
item.baseData.name = item.baseData.name.substr(0, 1024);
}
}
});

navigator.geolocation.getCurrentPosition() is not getting a response from googleapi

I am using react to get geolocation on localhost:3000. I have seen another person get the geolocation coordinates on their localhost, but I am unable to do so even with allow location access enabled on Chrome.
I have tried using both the hooks and class syntax in react. I have enabled allow access. I eventually used an ip address api to get a general location, but since the geolocation is supposed to work(at least that is what I have been told) I would at least like to see it work so I can implement it with https in the future. The error log does not even get fired, whereas the first three logs are getting fired when the component is mounted. Here is the code I have tried, I have made it as simple as possible:
const App = props => {
useEffect(() => {
console.log('hello')
console.log(navigator)
console.log(navigator.geolocation)
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
console.log(position)
}, (error) => {
console.log(error)
})
} else {
console.log('error')
}
}, [])
return (
<div>
<h3>Please Login.</h3>
</div>
)
}
export default App
I expect to receive a response from googleapi.
Edit:
I added the error callback and it printed:
message: "Network location provider at 'https://www.googleapis.com/' : No response received."
add the optional error callback to handle the error (if user declines location permission)
navigator.geolocation.getCurrentPosition(success[, error[, [options]])
you are checking only if it is in navigator or not !!!
if user declines location permission then error callback will handle it...
possible options are (reference taken from mdn)
{
enableHighAccuracy: true,
maximumAge : 30000,
timeout : 27000
}

Redux Form: Set error to a field without submitting the form

I have a form that is loading data from an API. I'm trying to set manually an error to the field if occurs some error in the api call.
// This is the input that I'm trying to set the error message
<Field
name="username"
component={CustomCombobox}
/>
Here I'm trying to set an error in the catch block.
try {
const { data } = await UserService.getUser();
} catch (e) {
// here I'm trying to set an error to "username" field
stopSubmit('myFormName', { username: 'Something wrong happened.' })
}
But here's is the problem. I'm not submitting the form, so the stopSubmit does not work. I'm just receiving data from an API to fill the options, and if some error happens I want to set the error manually.
This website has some examples on form validation
If you are trying to run a check on the username before submitting the form, you could run an API call on the value of the field and then show the error if the function fails.
Maybe this isn't what you are looking for / I have misunderstood

Custom remote validator error message

With a custom remote validator, how are you supposed to get rid of the error messages?
Using data-parsley-remote-validator='mycustom' on the field will give you an error in the console 'undefined async validator' unless the validator is added on DOM ready i.e not inside another function. However, if it is added on DOM ready, then parsley automatically calls it, which shouldn't happen until submit/change or whatever else you have set.
I can do something like this, but it kind of defeats the object of having parsley call the validator on change:
$('#signUpForm').on('submit', function() {
//add the attribute here to avoid the initial error message
$('#exampleInputEmail1').attr('data-parsley-remote-validator', 'validateEmail');
//then add the custom validator
$('#exampleInputEmail1').parsley()
.addAsyncValidator('validateEmail', function (xhr) {
if(xhr.status == '200') {
return 200;
}
// return the error message if email is taken
else if(xhr.status == '404') {
response = '<ul class="errorlist"><li>That email has already been taken, please try another</li></ul>'
$('#errorResponse').html(response);
}
}, '/api/v1/email/available', { "type": "POST", "dataType": "json", "data": data }
);
});
For those who came here for custom remote validator error message in Parsley.js,
You can add data-parsley-remote-message to the element,
<input type="text" data-parsley-remote-validator="my_remote_validator" data-parsley-remote-message="Custom error message only for remote validation on this element" >
Tested with Parsley.js - Version 2.3.11
Your asynch validator is not supposed to set an error message itself, it should simply return if the value validates or not. The error messages are added with a different API and/or specified as data attributes, check the doc.

Resources