functiondeepFunction(){thrownewError("Something broke");}try{deepFunction();}catch(err){console.log(err.name);// "Error"console.log(err.message);// "Something broke"console.log(err.stack);// Full stack trace string}
Note err.stack is not standardized but is supported everywhere in practice. It includes the error message and the call chain leading to where the error was created.
// Validate on change, blur, or submitconst errors ={};if(!value) errors.field='Required';
Example
functionSignupForm(){const[fields, setFields]=useState({ name:'', email:'', age:''});const[errors, setErrors]=useState({});const[touched, setTouched]=useState({});functionvalidate(data){const errs ={};if(!data.name.trim()) errs.name='Name is required';if(!data.email.includes('@')) errs.email='Invalid email';if(Number(data.age)<18) errs.age='Must be at least 18';return errs;}functionhandleChange(field, value){const updated ={...fields,[field]: value };setFields(updated);if(touched[field]){setErrors(validate(updated));}}functionhandleBlur(field){setTouched(prev =>({...prev,[field]:true}));setErrors(validate(fields));}functionhandleSubmit(e){
e.preventDefault();const errs =validate(fields);setErrors(errs);setTouched({ name:true, email:true, age:true});if(Object.keys(errs).length===0){submitSignup(fields);}}return(<form onSubmit={handleSubmit}><input
value={fields.name}
onChange={e =>handleChange('name', e.target.value)}
onBlur={()=>handleBlur('name')}/>{touched.name&& errors.name&&<span>{errors.name}</span>}{/* repeat for other fields */}<button type="submit">SignUp</button></form>);}
Note Validate on blur for a good UX: users see errors after leaving a field, not while typing. On submit, validate everything and mark all fields as touched. For complex forms, consider a form library or useReducer.
Frequently asked questions
How does JavaScript handle error message?
This task is covered in 2 stacks on this page: JavaScript, React. The "Working with Stack Traces" snippet in JavaScript uses `error.stack`.
Which code does the JavaScript example use?
The "Working with Stack Traces" snippet uses `error.stack`, from the Error Handling section of the JavaScript cheat sheet.
Which stacks cover "error message" on this page?
JavaScript, React. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Working with Stack Traces": err.stack is not standardized but is supported everywhere in practice. It includes the error message and the call chain leading to where the error was created.