> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# MigrationFailed 이벤트로 마이그레이션 실패 처리하기

> Laravel 13의 MigrationFailed 이벤트를 사용해 실패한 마이그레이션의 정보, 트랜잭션 경계, 모니터링과 테스트 설계를 이해합니다.

마이그레이션 실패를 모니터링하려면 `Illuminate\Database\Events\MigrationFailed`를 리스닝합니다. Laravel은 단일 마이그레이션 실행 중 예외가 발생하면 이 이벤트를 발행한 뒤 예외를 다시 던집니다.

이것은 마이그레이션을 자동으로 다시 실행하는 구조가 아닙니다. 실패한 이름, `up` / `down` 중 어느 쪽에서 실패했는지, 원래 예외를 로그나 알림으로 전달하기 위한 이벤트입니다.

## 이벤트가 가진 정보

`MigrationFailed`는 `MigrationEvent`를 상속하며, 단일 마이그레이션에 관한 다음 값을 공개합니다.

| 속성 | 타입 | 내용 |
| - | - | - |
| `migration` | `Migration` | 실행 대상 마이그레이션 인스턴스 |
| `method` | `string` | 호출된 메서드. 보통 `up` 또는 `down` |
| `name` | `string\|null` | 마이그레이션 이름. 실행 경로에 따라 `null` |
| `exception` | `Throwable` | 실패의 원인이 된 예외 |

`name`뿐만 아니라 `migration::class`도 기록하면 파일 이름을 얻을 수 없는 경로에서도 대상을 특정할 수 있습니다. `migration->getConnection()`을 사용하면 마이그레이션이 명시적으로 지정한 연결 이름도 확인할 수 있습니다.

## 리스너 등록하기

애플리케이션의 서비스 프로바이더에서 이벤트를 등록하고, 구조화된 컨텍스트와 원래 예외를 로그로 전달합니다.

```php theme={null}
<?php

namespace App\Providers;

use Illuminate\Database\Events\MigrationFailed;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Event::listen(MigrationFailed::class, function (MigrationFailed $event): void {
            Log::error('Database migration failed.', [
                'migration' => $event->name,
                'class' => $event->migration::class,
                'method' => $event->method,
                'connection' => $event->migration->getConnection(),
                'exception' => $event->exception,
            ]);
        });
    }
}
```

리스너는 실패 기록에 집중시키고, 스키마 변경이나 마이그레이션 재실행은 하지 않도록 합니다. 이벤트 후에 원래 예외가 다시 던져지므로 `php artisan migrate`와 `php artisan migrate:rollback`은 여전히 실패로 종료됩니다.

## 발행 순서

일반적인 단일 마이그레이션에서 `Migrator`는 다음 순서로 이벤트를 발행합니다.

```mermaid theme={null}
flowchart TD
    A["MigrationsStarted<br>배치 시작"] --> B["MigrationStarted<br>단일 마이그레이션 시작"]
    B --> C{"up / down 성공?"}
    C -->|성공| D["MigrationEnded<br>단일 마이그레이션 완료"]
    D --> E["다음 마이그레이션"]
    E --> F["MigrationsEnded<br>배치 완료"]
    C -->|예외| G["MigrationFailed<br>예외를 보유"]
    G --> H["원래 예외를 다시 던짐"]
```

`MigrationEnded`는 실행이 성공한 경우에만 발행됩니다. 마이그레이션 처리나 실행 중 발행된 이벤트의 리스너가 예외를 던지면 `runMigration`의 예외 처리로 들어가 `MigrationFailed`가 발행됩니다.

또한 배치 도중에 예외가 다시 던져지면 나머지 마이그레이션은 실행되지 않습니다. 따라서 실패한 배치에 대해 `MigrationsEnded`가 발행된다고 단정할 수 없습니다. 배치 완료 처리와 실패 시 처리를 같은 이벤트만으로 다루지 않도록 합니다.

## 트랜잭션과의 관계

데이터베이스의 Schema Grammar가 스키마 트랜잭션을 지원하고 마이그레이션의 `withinTransaction`이 활성화된 경우, Laravel은 실행을 트랜잭션으로 감쌉니다.

```php theme={null}
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('orders', function (Blueprint $table): void {
            $table->string('status');
        });
    }
};
```

이 경로에서 처리가 실패하면 트랜잭션 롤백 후에 `MigrationFailed`가 발행됩니다. 다만 다음과 같은 경우에는 데이터베이스가 모든 작업을 롤백할 수 있다고 단정할 수 없습니다.

* 사용하는 데이터베이스나 Schema Grammar가 스키마 트랜잭션을 지원하지 않음
* 마이그레이션에서 `public $withinTransaction = false`를 지정함
* 데이터베이스가 DDL을 트랜잭션으로 다루지 않음

따라서 이 이벤트를 받았다는 것만으로 스키마가 원래 상태로 돌아갔다고 판단하지 마세요. 실패한 환경에서는 실제 스키마와 `migrations` 테이블의 상태를 확인한 후 복구합니다.

## `up`과 `down`의 실패 구분하기

롤백 실패도 같은 이벤트로 통지됩니다. `method`를 확인하여 적용 시와 취소 시의 알림 대상이나 운영 절차를 나눌 수 있습니다.

```php theme={null}
Event::listen(MigrationFailed::class, function (MigrationFailed $event): void {
    $operation = $event->method === 'down' ? 'rollback' : 'migrate';

    Log::critical('Migration operation failed.', [
        'operation' => $operation,
        'migration' => $event->name ?? $event->migration::class,
        'exception' => $event->exception,
    ]);
});
```

`down`이 실패하면 대상 마이그레이션이 `migrations` 테이블에서 삭제되기 전에 예외가 발생합니다. `Migrator`는 `down`이 정상적으로 완료된 후에 삭제를 수행하므로, 실패 후에는 실제 스키마와 기록을 모두 확인합니다.

## 모니터링과 알림의 경계

`MigrationFailed`는 배포나 수동 Artisan 명령을 실행한 프로세스 안에서 동기적으로 처리됩니다. 알림을 큐에 넣으면 마이그레이션 명령 자체의 실패를 숨기지 않고 알림 전달을 후속 처리로 분리할 수 있습니다.

다만 실패한 마이그레이션을 리스너에서 다시 실행하는 것은 피합니다. 같은 명령이 종료되지 않은 상태에서 다시 실행하면 잠금, 부분적으로 적용된 DDL, 배포 순서 문제가 복잡해지기 때문입니다. 재실행이 필요한 경우 원인을 수정하고 상태를 확인한 후 운영 절차로 실행합니다.

## 테스트에서 이벤트 확인하기

실패하는 테스트용 마이그레이션을 준비하고, Artisan 명령이 실패하는 것과 이벤트가 원인 예외를 가지고 있는 것을 확인합니다. 테스트용 마이그레이션은 프로덕션의 탐색 대상에 두지 마세요.

```php theme={null}
<?php

namespace Tests\Feature;

use Illuminate\Database\Events\MigrationFailed;
use Illuminate\Support\Facades\Event;
use RuntimeException;
use Tests\TestCase;

class MigrationFailureTest extends TestCase
{
    public function test_failed_migration_dispatches_event(): void
    {
        Event::fake([MigrationFailed::class]);

        $this->artisan('migrate', [
            '--path' => 'tests/Fixtures/migrations/2026_01_01_000000_fail.php',
        ])->assertFailed();

        Event::assertDispatched(MigrationFailed::class, function (MigrationFailed $event): bool {
            return $event->method === 'up'
                && $event->exception instanceof RuntimeException;
        });
    }
}
```

`Event::fake`는 이벤트를 기록하므로 애플리케이션의 실제 알림 처리와 분리하여 테스트할 수 있습니다. 롤백 여부나 DDL이 부분적으로 남지 않는지는 사용하는 데이터베이스와 Schema Grammar를 사용한 별도의 통합 테스트로 확인합니다.

## 정리

* `MigrationFailed`는 단일 마이그레이션이 실패할 때 `migration`, `method`, `name`, `exception`을 전달합니다.
* `MigrationEnded`는 성공 시에만, `MigrationsEnded`는 배치가 끝까지 완료된 경우에 발행됩니다.
* 트랜잭션과 DDL 동작은 데이터베이스마다 다르므로 이벤트를 롤백 보장으로 다루지 않습니다.
* 리스너는 모니터링과 알림으로 한정하고, 재실행이나 복구는 원인과 스키마를 확인한 후 운영 절차로 수행합니다.

## 참고한 1차 정보

* [Laravel 공식 문서: 마이그레이션 이벤트](https://github.com/laravel/docs/blob/13.x/migrations.md#events)
* [Laravel 공식 문서: 이벤트 리스너](https://github.com/laravel/docs/blob/13.x/events.md#registering-events-and-listeners)
* [Framework 13.x: MigrationFailed](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Events/MigrationFailed.php)
* [Framework 13.x: MigrationEvent](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Events/MigrationEvent.php)
* [Framework 13.x: Migrator의 이벤트 발행](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Migrations/Migrator.php#L435-L460)
* [Framework 13.x: Migration 기반 클래스](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Migrations/Migration.php)


## Related topics

- [데이터베이스 마이그레이션](https://kawax.biz/ko/migrations.md)
- [고급 주제](https://kawax.biz/ko/advanced/index.md)
- [패키지 마이그레이션의 배포와 업데이트](https://kawax.biz/ko/advanced/package-migrations.md)
- [laravel/ui에서 Fortify로의 마이그레이션 가이드](https://kawax.biz/ko/blog/ui-to-fortify.md)
- [Testbench Workbench로 패키지 개발 진행하기](https://kawax.biz/ko/advanced/package-workbench.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.