Nuxt.js and Laravel Api - 422 Displaying Error instead of Forms - laravel

[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.

Related

Vue, SPA, Laravel. Erro with response

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.

error Policy in Apollo Client React does'nt work

I have aproblem when test Apollo.When I try query with apollo and graphql, i want response return error and partical data, so I set property errorPolicy:'all'. But its not work. I don't no why? Help please!
Here my code:
query { animal {
name
age }, school {
name
numberfd } } `
const { loading,data,error} = useQuery(GET_DASHBOARD_DATA, {
errorPolicy:'all',
onCompleted: (res) => {console.log("complete",res)},
onError : (res,data) => {console.log("ERRRR",res,data)},
})
and i want to receive:
{
error:[...], data:[animal:[...]] }
but its only response error.Here is Apollo's doc: https://www.apollographql.com/docs/react/data/error-handling/
onError type is onError?: (error: ApolloError) => void;. You don't have data inside onError callback.
After useQuery you can add:
console.log('data', data)
console.log('error', error)
I faced the same issue with errorPolicy: 'all', I only received the partial result inside onCompleted callback of useQuery, but no errors.
I created an ErrorLink like this:
private createErrorLink = () => {
return new ApolloLink((operation, forward) => {
return forward(operation).map((response) => {
// filter out errors you don't want to display
const errors = filterSomeErrors(response.errors);
if (errors && response?.data) {
response.data.errors = errors;
}
return response;
});
});
};
Now inside my onCompleted callback I get my data as well as errors. You will have to tweak your types a bit, because seems there is no errors field on response.data by default.
Mind that if you use onError from Apollo and return something from the link, it will retry your request containing errors!

How to pass a parameter in Koa middleware?

So I have this function in Koa, that basically checks if a user can access a specific route.
exports.requireRole = async role =>
async (ctx, next) => {
const { user } = ctx.state.user;
try {
const foundUser = await User.findById(user.id);
// If the user couldn't be found, return an error
if (!foundUser) {
ctx.status = 404;
ctx.body = { errors: [{ error: ERRORS.USER_NOT_FOUND }] };
} else {
// Otherwise, continue checking role
if (getRole(user.role) >= getRole(role)) {
await next();
}
ctx.status = 403;
ctx.body = { errors: [{ error: ERRORS.NO_PERMISSION }] };
}
} catch (err) {
ctx.throw(500, err);
}
};
And I want to use it as a middleware:
router.delete('/:id', combine([jwtAuth, requireRole(ROLES.ADMIN)]), deleteUser);
But then I get an error saying:
middleware must be a function not object
This happens only when I try to pass an argument into it.
What am I doing wrong here?
The issue you are having is due to the fact that Promises are objects, and async functions return Promises. You need to change your initial function to be as follows:
exports.requireRole = role =>
instead of
exports.requireRole = async role =>
I was going over middleware myself, and ran into this issue as well.
Your middleware looks fine, what is combine?
Also, since you are using koa-router you don't need it.
router.delete('/:id', jwtAuth, requireRole(ROLES.ADMIN), deleteUser);

Return axios Promise through Vuex

all!
I need to get axios Promise reject in my vue component using vuex.
I have serviceApi.js file:
export default {
postAddService(service) {
return axios.post('api/services', service);
}
}
my action in vuex:
actions: {
addService(state, service) {
state.commit('setServiceLoadStatus', 1);
ServicesAPI.postAddService(service)
.then( ({data}) => {
state.commit('setServiceLoadStatus', 2);
})
.catch(({response}) => {
state.commit('setServiceLoadStatus', 2);
console.log(response.data.message);
return Promise.reject(response); // <= can't catch this one
});
}
}
and in my vue component:
methods: {
addService() {
this.$store.dispatch('addService', this.service)
.then(() => {
this.forceLeave = true;
this.$router.push({name: 'services'});
this.$store.dispatch('snackbar/fire', {
text: 'New Service has been added',
color: 'success'
}).then()
})
.catch((err) => { // <== This never hapens
this.$store.dispatch('snackbar/fire', {
text: err.response.data.message || err.response.data.error,
color: 'error'
}).then();
});
}
When i use axios directly in my component all work well. I get both success and error messages.
But when i work using vuex i can't get error message in component, hoever in vuex action console.log prints what i need.
I'm always getting only successfull messages, even when bad things hapen on beckend.
How can i handle this situation using vuex ?
Wellcome to stackoverflow. One should not want to expect anything back from an action. After calling an action. Any response should be set/saved in the state via mutations. So rather have an error property on your state. Something like this should work
actions: {
async addService(state, service) {
try {
state.commit('setServiceLoadStatus', 1);
const result = await ServicesAPI.postAddService(service);
state.commit('setServiceLoadStatus', 2);
} catch (error) {
state.commit("error", "Could not add service");
state.commit('setServiceLoadStatus', 2);
console.log(response.data.message);
}
}
}
And in your component you can just have an alert that listens on your state.error
Edit: Only time you are going expect something back from an action is if you want to call other actions synchronously using async /await. In that case the result would be a Promise.

Karma/Jasmin Test Promise error inside of regular function

First my Setup. I try to test some of my Ionic Pages etc.
And I have a login page where I want to test the Login.
This is my Login method:
doLogin() {
let authHelper = this.injector.get(AuthHelper);
authHelper.sendSignInLink(this.email).then(()=> {
window.localStorage.setItem("userMail", this.email);
let loginToast = this.toast.create({
message: "Link to email succesfully send. In order to finish the login, it is necessary to click the send link.",
duration: 3000,
position: "bottom",
});
loginToast.present();
}).catch(() => {
throw new EmailSignInLinkError("invalid Mail");
});
}
As we can see the method sendSignInLink is returning a promise and if the promise is rejected it should throw a custom error.
For my unit test I mocked the authHelperClass to a very simple mock:
export class AuthHelperMock {
public auth(): Promise<any> {
return new Promise((resolve, reject) => {
resolve(2);
});
}
public sendSignInLink(email: String): Promise<any> {
return new Promise((resolve, reject) => {
if (email != undefined || email != "")
resolve(1);
else
reject("Invalid email");
});
}
}
Now is the Problem that I try to check on this thrown error from my promise.
My it case is:
it('should not do the login', () => {
component.email = "";
expect(() => {
component.doLogin();
}).toThrowError(EmailSignInLinkError)
I know that this will not work because the promise is async and the case will fail before it throws the error. But I don't find any suitable solution beside changing my doLogin to a promise as well.
How can I check on this Promise within a regular function?

Resources