atinux / nuxt-auth-utils

Add Authentication to Nuxt applications with secured & sealed cookies sessions.
MIT License
974 stars 91 forks source link

Error handling: Error not caught in error.vue #186

Closed awais019 closed 1 month ago

awais019 commented 1 month ago

I'm trying to return error from onError using sendError but it is not caught in error.vue. What is the better way to catch it?

atinux commented 1 month ago

You should use createError, see https://h3.unjs.io/guide/event-handler#error-handling

But I suggest to redirect most of the time in this onError hook and add query parameters to the route:

return sendRedirect(event, '/login?error=...')
awais019 commented 1 month ago

Thanks @atinux. I have also moved to this approach of query setting. But is it safe to send error like this error.toJSON() and then parse it on the query read.

awais019 commented 1 month ago
const error = JSON.parse(route.query.error as string);
    throw createError({
      statusCode: error.statusCode,
      statusMessage: error.statusMessage,
    });
atinux commented 1 month ago

If you throw the error from a server/routes/..., it will display the error.vue from Nuxt normally.

I would suggest to not give sensitive informations but mostly use from kind of code like /login?error=oauth_code

awais019 commented 1 month ago

I was trying to throw the error from onError function but createError doesn't seem to work in it. Here is how my auth/facebook route:

export default oauthFacebookEventHandler({
  onSuccess(event, { tokens }) {
    return sendRedirect(
      event,
      `/verify-facebook-signin/?fbAccessToken=${tokens.access_token}&type=facebook`,
    );
  },
  onError(event, error) {
    return sendRedirect(event, `/?error${error.toJSON()}`);
  },
});

then on index.vue I'm catching the error

if (route.query.error) {
    const error = JSON.parse(route.query.error as string);
    throw createError({
      statusCode: error.statusCode,
      statusMessage: error.statusMessage,
    });
  }