I can't show my error in my laravel vue js project.
My Controller
return response()->json(['error'=>'You Already Review This Product'], 422);
My Browser response successfully shows the error. The image in the link.
https://i.postimg.cc/yYB8mXmB/error.png
My Vue Component Script
reviewPost(){
this.$Progress.start();
this.review.post('/api/product/review')
.then(response=>{
Fire.$emit('getReview'+this.$route.params.slug);
this.review.reset();
Toast.fire({
icon: 'success',
title: response.data,
});
this.$Progress.finish();
})
.catch(error=>{
console.log(error);
Toast.fire({
icon: 'error',
title: 'Here i want to show my error',
});
this.$Progress.fail();
});
},
Console.log(error) showing this.
Error: Request failed with status code 422
at createError (app.js:702)
at settle (app.js:977)
at XMLHttpRequest.handleLoad (app.js:169)
Now How I Fix This Problem.
I think I understand your problem now. I have had to deal with similar processing myself.
Since it looks like the error returned has the JSON format:
{
"error": "You Already Review This Product"
}
you can add logic similar to this to your 'catch(error)':
.catch(error=>{
console.log(error);
if (error.response) {
if (error.response.status == 422) {
let errorMessage = error.response.data.error;
Toast.fire({
icon: 'error',
title: errorMessage,
});
this.$Progress.fail();
}
else {
console.error("Response contains error code " + error.response.status);
}
}
else if (error.request) {
console.error("No response received so logging request");
console.error(error.request);
}
else {
console.error("Problem with request: " + error.message);
}
});
BTW, I use Axios for calling REST APIs, and I'm not sure if other ways of calling REST APIs may use a different error structure. As you probably know, you can see the error object structure in the console log.
Related
I’m using FilePond 4.30.4 with React and react-filepond 7.1.2. Everything is working great and I can upload files.
My server responds with a file ID, and this comes back down to FilePond. I can see it in the onprocessfile event.
I’d like to include this is the ‘Upload Complete’ message. e.g. ‘Complete, file 12345’. How can I set this?
I’ve tried to update .labelFileProcessingComplete in onprocessfile, but it has no effect. I can see my events being fired and the correct data in the console. Perhaps there is another way to update the 'Upload Complete' label with a custom message for the file.
<FilePond
ref={filePondRef}
oninit={() => handleInit()}
files={files}
onupdatefiles={setFiles}
onprocessfile={ (error, file) => {
if (error) {
console.log('OnProcessFile: we have an error:' + error);
console.dir(error);
return;
}
console.log('OnProcessFile:File processed', file);
console.log('OnProcessFile:set processed message to ', file.serverId);
//This has no effect
filePondRef.current.labelFileProcessingComplete='Completed:-#' + file.serverId;
}
}
labelIdle='Drag & Drop your files or <span class="filepond--label-action">Browse</span>'
server={ {
timeout: 7000,
process: {
url: apiUrl,
method: 'POST',
withCredentials: false,
timeout: 7000,
onload: (res) => {
console.log('onload:and label with res=' + res);
// this has no effect either
filePondRef.current.labelFileProcessingComplete='Completed:' + res;
return res;
}
}
}
}
labelFileProcessingError= {() => {
// replaces the error on the FilePond error label
console.log('labelFileProcessingError: serverResponse is:' + serverResponse );
return serverResponse;
}}
/>
I am getting an error when I request. Оn the backend side there is a check that the name length is at least 3 characters. The response from the server is correct. but when I try to display an error, the message comes out saying that the answer was not found.
async saveBoard(id, index) {
await this.API.put("/boards/" + id, {
name: this.boards[index].name,
})
.then((response) => {
alert(response.data.message);
this.boards[index].etitable = !this.boards[index].etitable;
})
.catch((error) => {
console.log(error);
});
},
when I try to output error.response.date to the console, I get an error that response is not defined.
How can I solve this problem, why does axios not see the response from the server and the error code?
Error code must be in your catch You can't reach error message in then.
You are probably see error in your console right now
return response;
},
error => {
if (error.response.status == 401 || error.response.status == 419) {
const token = localStorage.getItem('token');
if (token) {
localStorage.removeItem('token');
}
const user = localStorage.getItem('user');
if (user) {
localStorage.removeItem('user');
}
router.push('/login');
} else {
if (error.response.status == 403) {
router.push('/');
}
}
return Promise.reject(error);
});```
I added a return to the interceptors function. Problem solved thanks for your help.
I am using Vue.js with Vue-Apollo and trying to fetch shared member list using query. I am using the graphQL service in backend.
I am using apollo 'error' function to handle GraphQL error. When the request is made with invalid input, I can see the errors in the network tab, I can see the JSON for the custom errors messages. But I can't console the errors in 'error' function.
Here is the apollo query that is used to fetch shared member list -
apollo: {
sharedMembers: {
query: gql`
query item($uuid: ID) {
item(uuid: $uuid) {
...itemTemplate
members {
...member
permission
}
}
}
${ITEM_TEMPLATE}
${MEMBER}
`,
variables() {
return {
uuid: this.$route.params.uuid,
}
},
update(data) {
return data.item.members
},
error(error) {
console.log('errors', error)
}
},
},
The network response I got -
network_error
Using graphQLErrors
You could get the errors by looking in the error object for graphQLErrors:
error(error) {
console.log('errors', error.graphQLErrors)
}
or
error({ graphQlErrors }) {
console.log('errors', graphQLErrors)
}
Using apollo-error-link
You can use apollo-error-link to help solve your problem if the above doesn't work, docs here.
Here's an example from the docs and I added to it in the networkErrors section to show what you can do to edit the error message you see in your error block, or catch block if its a mutation.
import { onError } from "apollo-link-error";
const link = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
if (networkError) {
// Add something like this to set the error message to the one from the server response
networkError.message = networkError.result.errors[0].debugMessage
console.log(`[Network error]: ${networkError}`)
};
});
And then in your code:
error(error) {
console.log('error-message', error.message)
}
The console should then log your debugMessage from the server.
unfortunately i couldn't find out how i'd handle errors in such of graphql method call, but as an option you could provide onError method to ApolloClient constructor options. first argument is the error object. hopefully it may help. like so..
const apolloClient = new ApolloClient({
uri: 'http://localhost:4000',
onError(err) {
console.log(err)
},
})
[Error][1]
Hi Team,
Whenever I am receiving the error return from laravel the nuxt.js project displays the error on the page instead the HTML/Forms. How can i handle this.
Here is my php code
return response()->json([
'errors' => [
'email' => ['Sorry we cant find you with those details.'],
],
], 422);
Javascript
async submit() {
await this.$auth.loginWith("local", {
data: this.form
})
In your JavaScript you need to wrap your await promise inside a try catch block. Here's a fix for your JS.
try {
await this.$auth.loginWith("local", {
data: this.form
})
} catch (e) {
return;
}
This is an old question at this point, but I thought I'd post the full code since I was pretty stumped and didn't find many great answers out there:
async handleSubmit() {
try {
const authResponse = await this.$auth.loginWith('local', {
data: this.formData
});
const { status, data } = authResponse;
if (status === 200)
this.createFlashAlert({ 'success': 'Login successful' });
} catch (error) {
if (error.response.status === 422)
this.createFlashAlert(error.response.data);
}
}
So the checklist:
Wrap the login call in a try/catch if you're using async await syntax (be sure to make it an async function i.e. async handleSubmit.
in the catch block, use the error.response object, this is an axios thing. With this you'll be able to access the response status and data.
If you log just the error object, it's not obvious that you can access the response within that error which is what had me stumped.
I am currently learning react-native and I am having an issue with fetch request.
It's giving me an error in the image shown below.
**Note: I test the url with react, and it works there. But for some reason it does not work on react-native.
The code:
constructor(props) {
super(props);
this.state = {
isLoading: true,
data: null,
error: null
}
}
componentDidMount() {
return fetch('https://ptx.transportdata.tw/MOTC/v2/Bike/Availability/Taipei?$format=JSON')
.then((res) => res.json())
.then((resJson) => {
this.setState( {
isLoading: false,
data: resJson,
})
})
.catch((error) => {
console.log(error);
this.setState({
error: error
})
})
}
The error is the following:
error description
A few things:
You don't need a return statement in componentDidMount.
When I try to fetch the URL, I got a 401 unauthorized. According to their API docs you need an app id and api key. Are you setting those when making the request?