본문 바로가기

Java Scripts/Vue.js

Vue : Error Handling and 404s

728x90

Error Handling and 404s

There are three different kinds of errors we need to catch in our application.

애플리케이션에서 잡아내야 하는 세 가지 종류의 오류가 있습니다.

  • When a user tries to navigate to a page that doesn’t exist.
  • 사용자가 존재하지 않는 페이지로 이동하려고 할 때.
  • When a user’s network connectivity fails.
  • 사용자의 네트워크 연결이 실패하는 경우.
  • When a user tried to go to an event that doesn’t exist.
  • 사용자가 존재하지 않는 이벤트로 이동하려고 한 경우.

 

Problem: The Generic Not Found 404

Right now when I go to a URL that doesn’t exist I get a blank page with no information about what is going on.

지금 존재하지 않는 URL로 이동하면 무슨 일이 일어나고 있는지에 대한 정보가 없는 빈 페이지가 나타납니다.

 

Solution: A Not Found Component

Let’s create a generic  Not Found Component that we’ll redirect to when a path is accessed that doesn’t exist.

존재하지 않는 경로에 액세스할 때 리디렉션할 generic  Not Found Component 를 만들어 보겠습니다.

 

/src/views/NotFound.vue

<template>
  <h1>Oops!</h1>
  <h3>The page you're looking for is not here.</h3>
  <router-link :to="{ name: 'EventList' }">Back to the home page</router-link>
</template>

we need to render this component when we go to a catch-all route, by updating our router.js file.

router.js 파일을 업데이트하여, catch-all route로 이동할 때  이 component를 렌더링해야 합니다.

 

 

 /src/router/index.js

...
import NotFound from '@/views/NotFound.vue'

const routes = [
  ...
  {
    path: '/:catchAll(.*)',
    name: 'NotFound',
    component: NotFound
  }
]

Creating a path that catches everything that hasn’t matched a current route. and redirecting to the 404 path when we hit our new catch-all route.

현재 route와 일치하지 않는 모든 것을 catch하는 path를 만듭니다. 새로운 catch-all route에 도달하면 404 path 로 리디렉션됩니다.

 

 

Problem: What about when we try to view a non-existent Event?

when we go to an event that doesn’t exist, like /event/1233.

/event/1233과 같이 존재하지 않는 이벤트로 이동하는 경우

 

Solution: Creating a 404 page for a Non-Existent Event

A prop called resource which will default to page is added. if this component is loaded without the prop, the text will read “The page you’re looking for is not here”. if I can send in event as the value of resource and it will read “The event you’re looking for is not here.”

페이지로 기본 설정되는 리소스라는 prop이 추가됩니다. 이 component 가 prop 없이 로드되면 “The page you’re looking for is not here”라는 텍스트가 표시됩니다. 이벤트를 리소스 값으로 보내면 “The event you’re looking for is not here.”라는 메시지가 표시됩니다.

 

 

/src/views/NotFound.vue

<template>
  <div>
    <h1>Oops!</h1>
    <h3>The {{ resource }} you're looking for is not here.</h3>
    <router-link :to="{ name: 'EventList' }">Back to the home page</router-link>
  </div>
</template>
<script>
export default {
  props: {
    resource: {
      type: String,
      required: true,
      default: 'page'
    }
  }
}
</script>

 

/src/router/index.js

This route takes a prop.

이 경로에는 prop이 필요합니다.

...
{
  path: '/404/:resource',
  name: '404Resource',
  component: NotFound,
  props: true
},
...

 

 

/src/views/Layout.vue

Redirect the user if the API request when fetching an event returns an error:

이벤트를 가져올 때 API 요청이 오류를 반환하는 경우 사용자를 리디렉션합니다.

  ...
  created() {
    EventService.getEvent(this.id)
      .then(response => {
        this.event = response.data
      })
      .catch(error => {
        console.log(error)

        this.$router.push({ name: '404Resource', params: { resource: 'event' } })
      })
  }
  ...

 

 

Problem: Errors won’t always be 404

There is possibility in assuming all network errors we receive are 404 errors.

우리가 받는 모든 네트워크 오류가 404 오류라고 가정할 가능성이 있습니다.

However, what if the user’s Internet just died or they’re on a super slow connection? We don’t want to give them a 404 error if their Internet dies,

하지만 사용자의 인터넷이 방금 중단되었거나 연결 속도가 매우 느린 경우에는 어떻게 될까요? 인터넷이 중단되면 404 오류를 발생하고 싶지 않습니다.

 

Solution: A NetworkIssue component

  1. Create a new NetworkIssue component. 새로운 NetworkIssue component 생성
  2. Add NetworkIssue to the router.  라우터에 NetworkIssue 추가
  3. detect 404 error vs other network error.  404 오류와 다른 네트워크 오류 감지
  4. Add a timeout to our axios API call.  axios API 호출에 시간 초과를 추가합니다.

/src/views/NetworkError.vue

Using the $router.go(-1) method here to push the user back to the previous page which triggered the network error.

여기에서 $router.go(-1) 메소드를 사용하여 사용자를 네트워크 오류를 발생시킨 이전 페이지로 되돌립니다.

<template>
  <div class="networkError">
    <h1>Uh-Oh!</h1>

    <h3>
      It looks like you're experiencing some network issues, please take a breath and
      <a href="#" @click="$router.go(-1)">click here</a> to try again.
    </h3>
  </div>
</template>

 

/src/router/index.js

add this to our router:

{
 path: '/network-error',
 name: 'NetworkError',
 component: NetworkError
},

 

/src/views/Layout.vue

we need to check which type of network error we’ve encountered so we can push to the appropriate path inside our Layout.vue:

Layout.vue 내부의 적절한 경로로 푸시할 수 있도록 어떤 유형의 네트워크 오류가 발생했는지 확인해야 합니다.

...
  created() {
    EventService.getEvent(this.id)
      .then(response => {
        this.event = response.data
      })
      .catch(error => {
        if (error.response && error.response.status == 404) {
          this.$router.push({ name: '404Resource', params: { resource: 'event' } })
        } else {
          this.$router.push({ name: 'NetworkError' })
        }
      })
  }
...

Sample Codes

https://github.com/Code-Pop/Touring-Vue-Router/tree/L7-end

 

GitHub - Code-Pop/Touring-Vue-Router

Contribute to Code-Pop/Touring-Vue-Router development by creating an account on GitHub.

github.com

 

'Java Scripts > Vue.js' 카테고리의 다른 글

Vue MultiSelect  (0) 2022.04.09
Vue 3 -Teleport  (0) 2022.03.22
Vue - Progress Bar : Axios Interceptors  (0) 2022.01.12
Vue : API calls with Axios  (0) 2022.01.08
Vue : Global Component  (0) 2022.01.08