I'm a beginner in reactjs, I'm having trouble displaying error messages from the API, the error message looks in this way
"[ErrorDetail(string=' name already exists!', code='invalid')]"
I only need the "string" value here, so I'm looking for a way to extract it from the error message above.
in react, using
const errMsg = err?.response?.data?.error?.message
this.setState(common.showSnackbar(true, errMsg || err.message || err, 'error'))
give me if there is a solution to change message from this
[ErrorDetail(string=' name already exists!', code='invalid')]
to
'name already exists!'
You can use a regular expression:
// this extracts the string and the code part
const regex = /\[\w+\(\w+='(.*)',\s\w+='(.*)'\)\]/g;
const parsed = regex.exec("[ErrorDetail(string=' name already exists!', code='invalid')]");
console.log(parsed[1]); // ' name already exists!'
console.log(parsed[2]); // 'invalid'
This assumes the format of the string is always as you posted.
I'd suggest playing around with the regex in https://regexr.com to change it to fit your problem.
If you have control of the Django API, you could fix it before it ever gets to the browser.
The ErrorDetail instance is a string-like object. What you're seeing is the __repr__() method's representation of the object. To get the plain string from it you just need to wrap the instance in str().
Then your data.error.message will just be name already exists!