question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Catching 404 errors on server side

See original GitHub issue

Describe the problem

Some code a while go worked perfectly:

__error.js

import customFetch from '$lib/customFetch'
import { setCookie } from '$lib/helpers'

export async function load ({ url, error, status }) {
  if (status === 404 && !(url.pathname.substring(1)).includes('/')) {
    return await customFetch
      .service('api/redirects')
      .get(url.path.substring(1))
      .then(redirect => {
        if (redirect.cookie) {
          setCookie(redirect.cookieName, redirect.cookieValue)
        }
        return {
          status: redirect.status,
          redirect: redirect.location
        }
      })
      .catch(() => {
        return {
          props: {
            status: status,
            error: error.message
          }
        }
      })
  } else {
    return {
      props: {
        status: status,
        error: error.message
      }
    }
  }
}

but now none of this will work, and I cannot make it work in any way other than in a way that loads the whole site.

This is used in 2 ways.

  1. If you change the structure of your site, for SEO reasons, you want a 301 redirect.

  2. I also use it for short links for affiliate forwarding using a 307 redirect.

The load function also doesn’t have error or status so I cannot do it in +layout.server.js

Describe the proposed solution

Allow +error.js or +error.server.js files, or have the error in +layout.server.js??

Alternatives considered

No response

Importance

would make my life easier

Additional Information

No response

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:1
  • Comments:14 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
L1xx3rcommented, Oct 11, 2022

@dummdidumm the following works perfectly. Thanks for your help:

import env from '$lib/env'
import { error, redirect } from '@sveltejs/kit'
import got from 'got'
import _ from 'lodash'

export async function load ({ url }) {
  let e404 = false
  let redirectObj = {}

  const sitePage = await got(`${env.api}/site-pages/?pathname=${encodeURI(url.pathname)}`)
    .then(response => {
      let obj = JSON.parse(response.body)
      obj = obj.data || obj
      if (obj[0]) {
        return obj[0]
      } else {
        e404 = true
        return null
      }
    })
    .catch((e) => {
      console.error(e)
      e404 = true
    })

  if (e404) {
    redirectObj = await got(`${env.api}/redirects/?pathname=${url.pathname}`)
      .then(response => {
        let obj = JSON.parse(response.body)
        obj = obj.data || obj
        if (obj[0]) {
          return obj[0]
        }
      })
      .catch((e) => {
        console.error(e)
        e404 = true
      })
  }

  if (!_.isEmpty(redirectObj)) throw redirect(redirectObj.status, redirectObj.location)
  if (e404) throw error(404, 'not-found')

  return {
    sitePage
  }
}
1reaction
L1xx3rcommented, Oct 11, 2022

HAhaha wait a sec, I am catching the throw… lol My bad!

Read more comments on GitHub >

github_iconTop Results From Across the Web

404 Not Found Pages | Error Handling - YouTube
404 Not Found Pages Error Handling Server Server Side Rendering with React and ReduxSubscribe ...
Read more >
How To Find & Fix 404 Errors On Your Website | Matthew Edgar
One of the more popular tools for checking broken links that lead people to 404 errors on your website is the broken link...
Read more >
How To Properly Serve 404 Errors on SPAs (with SEO in Mind)
Out of the box, 404 error pages in SPAs don't work properly, creating problems for SEO. Here we'll review the pros and cons...
Read more >
404 Not Found Error: What It Is and How to Fix It - Airbrake Blog
A HTTP 404 error happens when a resource is unavailable. The client (web browser) received a message from the server (remote computer) that...
Read more >
c# - How can I catch a 404? - Stack Overflow
How can I catch a specific 404 error? The WebExceptionStatus.ProtocolError can only detect that an error occurred, but not give the exact code...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found