> ## Documentation Index
> Fetch the complete documentation index at: https://inertiajs-vi.tuantq.online/llms.txt
> Use this file to discover all available pages before exploring further.

# Xử lý lỗi

<Warning>Bạn đang xem tài liệu Inertia.js v2. Inertia.js v3 đã được phát hành và hiện là phiên bản mặc định. Hãy xem [hướng dẫn nâng cấp](/v3/getting-started/upgrade-guide) để bắt đầu.</Warning>

## Môi trường phát triển

Một lợi thế khi làm việc với server-side framework mạnh là bạn được hưởng sẵn cơ chế xử lý exception. Ví dụ, Laravel đi kèm công cụ báo lỗi trực quan, hiển thị stack trace được định dạng rõ ràng trong môi trường phát triển local.

Khó khăn nằm ở chỗ khi bạn thực hiện request XHR (như Inertia vẫn làm) và gặp lỗi phía máy chủ, thông thường bạn phải mở tab Network trong devtools của trình duyệt để lần tìm và chẩn đoán vấn đề.

Inertia giải quyết vấn đề này bằng cách hiển thị mọi response không phải Inertia trong một modal. Nhờ vậy, bạn vẫn có trải nghiệm báo lỗi trực quan quen thuộc dù request được thực hiện qua XHR.

## Phần tử Dialog

Mặc định, Inertia hiển thị error modal bằng một overlay `<div>` tùy chỉnh. Tuy nhiên, bạn có thể chọn dùng phần tử HTML `<dialog>` nguyên bản, vốn cung cấp chức năng modal tích hợp sẵn bao gồm cả xử lý backdrop.

Để bật tính năng này, hãy cấu hình tùy chọn `future.useDialogForErrorModal` trong [cấu hình mặc định của ứng dụng](/v2/installation/client-side-setup#configuring-defaults).

```js theme={null}
createInertiaApp({
    // resolve, setup, etc.
    defaults: {
        future: {
            useDialogForErrorModal: true,
        },
    },
})
```

## Production

Trong production, bạn nên trả về response lỗi Inertia phù hợp thay vì dựa vào cơ chế báo lỗi qua modal dành cho môi trường phát triển. Để làm vậy, bạn cần cập nhật exception handler mặc định của framework để trả về một trang lỗi tùy chỉnh.

Khi xây dựng ứng dụng Laravel, bạn có thể thực hiện việc này bằng phương thức exception `respond` trong file `bootstrap/app.php` của ứng dụng.

```php theme={null}
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Inertia\Inertia;

->withExceptions(function (Exceptions $exceptions) {
    $exceptions->respond(function (Response $response, Throwable $exception, Request $request) {
        if (! app()->environment(['local', 'testing']) && in_array($response->getStatusCode(), [500, 503, 404, 403])) {
            return Inertia::render('ErrorPage', ['status' => $response->getStatusCode()])
                ->toResponse($request)
                ->setStatusCode($response->getStatusCode());
        }

        if ($response->getStatusCode() === 419) {
            return back()->with([
                'message' => 'The page expired, please try again.',
            ]);
        }

        return $response;
    });
})
```

Có thể bạn nhận thấy ví dụ trên trả về page component `ErrorPage`. Bạn cần thực sự tạo component này; nó sẽ đóng vai trò trang lỗi dùng chung cho ứng dụng. Dưới đây là một component lỗi mẫu để bạn dùng làm điểm khởi đầu.

<CodeGroup>
  ```vue Vue icon="vuejs" theme={null}
  <script setup>
  import { computed } from 'vue'

  const props = defineProps({ status: Number })

  const title = computed(() => {
      return {
          503: '503: Service Unavailable',
          500: '500: Server Error',
          404: '404: Page Not Found',
          403: '403: Forbidden',
      }[props.status]
  })

  const description = computed(() => {
      return {
          503: 'Sorry, we are doing some maintenance. Please check back soon.',
          500: 'Whoops, something went wrong on our servers.',
          404: 'Sorry, the page you are looking for could not be found.',
          403: 'Sorry, you are forbidden from accessing this page.',
      }[props.status]
  })
  </script>

  <template>
      <div>
          <h1>{{ title }}</h1>
          <div>{{ description }}</div>
      </div>
  </template>
  ```

  ```jsx React icon="react" theme={null}
  export default function ErrorPage({ status }) {
      const title = {
          503: '503: Service Unavailable',
          500: '500: Server Error',
          404: '404: Page Not Found',
          403: '403: Forbidden',
      }[status]

      const description = {
          503: 'Sorry, we are doing some maintenance. Please check back soon.',
          500: 'Whoops, something went wrong on our servers.',
          404: 'Sorry, the page you are looking for could not be found.',
          403: 'Sorry, you are forbidden from accessing this page.',
      }[status]

      return (
          <div>
              <H1>{title}</H1>
              <div>{description}</div>
          </div>
      )
  }
  ```

  ```svelte Svelte 4 icon="s" theme={null}
  <script>
      export let status

      $: title = {
          503: '503: Service Unavailable',
          500: '500: Server Error',
          404: '404: Page Not Found',
          403: '403: Forbidden',
      }[status]

      $: description = {
          503: 'Sorry, we are doing some maintenance. Please check back soon.',
          500: 'Whoops, something went wrong on our servers.',
          404: 'Sorry, the page you are looking for could not be found.',
          403: 'Sorry, you are forbidden from accessing this page.',
      }[status]
  </script>

  <div>
      <h1>{title}</h1>
      <div>{description}</div>
  </div>
  ```

  ```svelte Svelte 5 icon="s" theme={null}
  <script>
      let { status } = $props()

      const title = {
          503: '503: Service Unavailable',
          500: '500: Server Error',
          404: '404: Page Not Found',
          403: '403: Forbidden',
      }

      const description = {
          503: 'Sorry, we are doing some maintenance. Please check back soon.',
          500: 'Whoops, something went wrong on our servers.',
          404: 'Sorry, the page you are looking for could not be found.',
          403: 'Sorry, you are forbidden from accessing this page.',
      }
  </script>

  <div>
      <h1>{title[status]}</h1>
      <div>{description[status]}</div>
  </div>
  ```
</CodeGroup>

***

## Tài liệu chính thức

Bài dịch này được đối chiếu từ [tài liệu Inertia.js v2 chính thức](https://inertiajs.com/docs/v2/advanced/error-handling). Nếu có khác biệt do phiên bản hoặc cập nhật mới, hãy ưu tiên tài liệu chính thức làm nguồn tham chiếu.
