0

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!'
1
  • 1
    Do you control the Django API? If so, you could extract the string from the ErrorDetail object and put that as the message, rather than the string representation of the object. Commented Feb 25, 2022 at 7:18

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.