[Vuejs]-Unable to customize form errors because server is returning 422 Unprocessable Entity without returning errors

0👍

Laravel returns the HTTP 422 - Unprocessable Entity when the validations you set fail. In your case I would take a closer look at the data you’re posting to the server and manually check if it passes the validation cases you wrote.

To get the exact fields that are causing the error you need to handle this in your code, like this for example:

$validator = Validator::make($data, $rules);

if ($validator->fails()) {

  // 500 is the HTTP Status Code you want to return.   
  // This should also throw you in the catch branch of your front-end code
  return response()->json(['errors'=>$validator->errors()], 500);

}

In your code the $data variable from the register function should be checked if it fails validation and return the error

0👍

This is because err will return the toString() method when accessed directly, but has properties:

err.response.data will have what you’re looking for.

0👍

When Axios throws an error, the HTTP response can be found in error.response. Validation errors will be in the errors key, so you can access validation errors like this:

axios.post(someUrl, someData)
    .then(response => {
        // Successful response
    })
    .catch(error => {
        let errors = error.response.data.errors;
    });

0👍

When there’s an HTTP error (e.g. a response code between 400 and 599) axios returns an axios error response and in the repository documentation under error handling it indicates that you can access the actual response using error.response.data. For example:

 try {
       const res=await axios.post('api/register',
       {
           email:this.form.email,
           password:this.form.password,
           password_confirmation:this.form.password_confirmation,
           fname:this.form.fname,
           lname:this.form.lname,
           city:this.form.city
       });
       //Une fois inscrit,il est redirige vers la page de login
       this.$router.push({path:'/login'});
       console.log("My data : ",res.data);
   }catch(err){
       if (err.response && err.response.status === 422) {
           if (err.response.data.errors.fname) {
              console.log('First name errors: '+ err.response.data.errors.fname.join(','));
           } 

           // and so on

       }
   }

Leave a comment