Nuxt.js - 'error not defined' when trying to throw 404 in failed await call within asyncData method - vue.js

Starting to play with Nuxt.js this evening and mock blog data but having an issue with non existing data.
Heres my asyncData method when viewing a single blog post:
async asyncData({ params }) {
try {
const post = await axios.get(
`https://jsonplaceholder.typicode.com/posts/${params.id}`
)
return {
post: post.data
}
} catch (err) {
error({ statusCode: 404, message: 'Post not found' })
}
}
When visiting a valid ID and a 200 error is returned everything works as expected, but when the endpoint returns a 404 it tells me that 'error is undefined'
I could only find information on doing this error handling using a promise catch method as seen here: https://nuxtjs.org/guide/async-data/#handling-errors
How can I use the error method within the try catch error?
Thanks.

You have to inject the error object in your asyncData method to use it inside:
async asyncData({ error, params }) {
// your code
}

Related

Handling 422 error with axios inside service.js

I have a service.js which has some axios requests. When I post something using this service from view, I can't handle errors, because all errors falls into success chain instead of error.
This line is from service.js
async createIsp(payload) {
return await apiService.post('/isp', payload)
}
And this one is from view:
function saveIsp() {
clicked.value = true
ApiService.createIsp({isp_name: newIsp.value}).then((data) => {
clicked.value = false
//all response falls here... even its error.
//router.push({name: 'isp'})
}).catch(e => console.log(e))
https://stackoverflow.com/a/70542347/3054818
This is the solution. I am using interceptors, and I should throw error.

Vuejs error after passing axios interceptor

I have a problem that I can't solve with vue.js
I intercept queries that return an error (axios interceptor), and when it passes through this interceptor, the catch of the axios query is still taken into account.
Except that I wait for an error "error.api". which I don't receive, so it generates a console error.
Here is the code:
axios.interceptors.response.use(null, error => {
let path = '/login';
switch (error.response.status) {
case 401: path = '/login'; break;
case 404: path = '/404'; break;
}
store.commit('logout')
router.push(path);
return Promise.reject(error);
});
this error
2.js:376 Uncaught (in promise) TypeError: Cannot read property 'api' of undefined
And finally, the axios query and the error is generated by the last line (err.api[0])
deleteApi(id) {
this.$store.dispatch('deleteApi', id)
.then((res) => {
this.$toast.success(res.data.success)
this.deleteApiModal(id)
})
.catch(err => this.$toast.error(err.api[0]))
},
I finally found a solution but very dirty, which I find repetitive for not much.
It's on each call axios, to put a condition that checks if "err" exists...
I would have preferred to be able to interact on the interceptor to have managed this in only one place.
If someone has a better solution, I'll take it !
deleteApi(id) {
this.$store.dispatch('deleteApi', id)
.then((res) => {
this.$toast.success(res.data.success)
this.deleteApiModal(id)
})
.catch(err => { if(err) this.$toast.error(err.api[0]) })
},

Vuex action "not a function" inside Nuxt fetch

I have just introduced error handling to one of my Nuxt pages and apparently the action mapped and called inside fetch raises a not a function error. If the try/catch block isn't there it works as expected and there's no error at all.
Here is my component stripped to the essential parts:
export default {
name: 'ViewArticle',
async fetch ({ error }) {
try {
await this.fetchArticle({ articleSlug: this.articleSlug })
} catch (err) {
error({ statusCode: 404, message: 'May the force be with you' })
}
},
computed: {
...mapGetters({
article: 'article/single'
}),
articleSlug () {
return this.$route.params.articleSlug
}
},
methods: {
...mapActions({
fetchArticle: 'article/fetchOne'
})
}
}
I am assuming that somehow mapActions only gets executed later in the spiel, but can't figure out how to prevent the error. This way, basically every time I load the page it gets immediately redirected to the error page.
The error message I'm getting is the following. Obviously fetchArticle is a function, and unless it's inside the try/catch block, it works as expected.
this.fetchArticle is not a function 03:30:51
at Object.fetch (52.js:32:18)
at server.js:2881:39
at Array.map (<anonymous>)
at module.exports../.nuxt/server.js.__webpack_exports__.default (server.js:2864:51)
Fetch provides the context as argument.
fetch(context)
Inside the context we can find our store. Here you can take a look what context contains: https://nuxtjs.org/api/context
fetch(context) {
let store = context.store;
}
People like to destructure it
fetch({ store }) {}
Your code should look like this:
async fetch ({ error, store }) {
try {
await store.dispatch('article/fetchOne', { articleSlug: this.articleSlug })
} catch (err) {
error({ statusCode: 404, message: 'May the force be with you' })
}
},
Fetch gets executed on the server side, thats why you get is not an function error. Its undefined
... fetch is called on server-side...
Use async fetch({store})
async fetch ({ error, store }) {
try {
await store.dispatch( 'article/fetchOne' , { articleSlug: this.articleSlug })
} catch (err) {
error({ statusCode: 404, message: 'May the force be with you' })
}

Error handling in HAPI

Catch all and any errors in a hapi request lifecycle.
I have a signup handler,
public signup(request: Hapi.Request, reply: Hapi.Base_Reply) {
this.database.user.create(request.payload).then((user: any) => {
return reply({
"success": true
});
}).catch((err) => {
reply(Boom.conflict('User with the given details already exists'));
});
}
Now, I am catching the error, but I can't be always sure that I will get this error message only. What if there is an error in the database?
How to catch such database errors or any other unknown errors for all the requests. ???
Maybe you have to return the err.message in your reply like
reply(Boom.conflig(err.message))
or if you want to manage or manipulate the error you have to verify the type of error like
if (err instanceof DatabaseError) {
// manage database error
}
I figured out a way to handle such errors in Hapi.
What I was looking for was a PreResponse handler. Now, the PreResponse handler can log all the errors and I can throw a 500 error response.
What I am saying is by simply writing
reply(err)
I can send a 500 error and can catch this error using preResponse handler. Something like this,
server.ext('onPreResponse', (request: Hapi.Request, reply: Hapi.ReplyWithContinue) => {
const response = request.response;
if (!response.isBoom) { // if not error then continue :)
return reply.continue();
}
console.log(response);
return reply(response);
});

expressjs not throwing error on Parse queries (parse-server)

I have a parse-server setup on expressjs like here.
But sometimes it's not showing errors inside Parse functions. Example:
// Parse Server is setup
// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
var pageQuery = new Parse.Query('Page');
pageQuery.get('id').then(function(page) {
someObject.undefinedProp = false;
res.send(page);
}, function(error) {
res.send(error);
});
});
No errors displayed, but with this code:
// Parse Server is setup
// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
someObject.undefinedProp = false;
res.send('ok');
});
I have this error displayed:
ReferenceError: someObject is not defined
(For this example I have the exact same configuration as the Parse Server Example)
I just want to have the errors displayed inside my Parse functions.
Any ideas?
Thank you for your help!
Your issue is actually an issue caused by Promises.
When you call pageQuery.get('id'), the get method returns a Promise instance. The then method of the Promise is how you set up your callback that will fire on the successful completion of the get operation.
In order to get a reference to the error that should occur when you attempt to reference someObject.undefinedProp, you'll also need to set up an error handler on that Promise object by calling its catch method.
app.get('/', function(req, res) {
var pageQuery = new Parse.Query('Page');
pageQuery.get('id').then(function(page) {
someObject.undefinedProp = false;
// the error thrown here will be caught by the Promise object
// and will only be available to the catch callback below
res.send(page);
}, function(error) {
// this second callback passed to the then method will only
// catch errors thrown by the pageQuery.get method, not errors
// generated by the preceding callback
res.send(error);
}).catch(function (err) {
// the err in this scope will be your ReferenceError
doSomething(err);
});
});
Here, check out the following article and scroll down to the section heading "Advanced mistake #2: catch() isn't exactly like then(null, ...)".
https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html