Store error details of failed imports and show them in the admin panel

The importers keep the original exception as the previous exception, so the
exception chain and stack trace can be stored in the new error_details column.
The details are only visible in the admin panel, which now also links the
organization and user of an import.
This commit is contained in:
Constantin Graf
2026-11-18 18:24:00 +01:00
committed by Constantin Graf
parent 4c8215a889
commit e44a3733e1
17 changed files with 128 additions and 18 deletions

View File

@@ -48,10 +48,27 @@ class ImportResource extends Resource
Select::make('organization_id')
->label('Organization')
->relationship(name: 'organization', titleAttribute: 'name')
->hintAction(
Action::make('open-organization')
->label('Open organization')
->icon('heroicon-o-arrow-top-right-on-square')
->url(fn (?Import $record): ?string => $record !== null
? OrganizationResource::getUrl('view', ['record' => $record->organization_id])
: null)
)
->disabled(),
Select::make('user_id')
->label('User')
->relationship(name: 'user', titleAttribute: 'email')
->hintAction(
Action::make('open-user')
->label('Open user')
->icon('heroicon-o-arrow-top-right-on-square')
->hidden(fn (?Import $record): bool => $record?->user_id === null)
->url(fn (?Import $record): ?string => $record?->user_id !== null
? UserResource::getUrl('view', ['record' => $record->user_id])
: null)
)
->disabled(),
TextInput::make('type')
->label('Type')
@@ -77,6 +94,15 @@ class ImportResource extends Resource
->label('Error message')
->columnSpanFull()
->disabled(),
Textarea::make('error_details')
->label('Error details')
->helperText('Exception chain and stack trace, only visible in the admin panel')
// The attribute is hidden for serialization, so it is not filled into the form automatically
->formatStateUsing(fn (Import $record): ?string => $record->error_details)
->rows(15)
->extraInputAttributes(['style' => 'font-family: monospace; font-size: 80%;'])
->columnSpanFull()
->disabled(),
PrettyJsonField::make('report')
->formatStateUsing(fn (Import $record): ?string => $record->getRawOriginal('report'))
->columnSpanFull()
@@ -102,10 +128,14 @@ class ImportResource extends Resource
return $table
->columns([
TextColumn::make('organization.name')
->url(fn (Import $record): string => OrganizationResource::getUrl('view', ['record' => $record->organization_id]))
->searchable()
->sortable(),
TextColumn::make('user.email')
->label('User')
->url(fn (Import $record): ?string => $record->user_id !== null
? UserResource::getUrl('view', ['record' => $record->user_id])
: null)
->searchable()
->toggleable(),
TextColumn::make('type')

View File

@@ -26,6 +26,7 @@ use Illuminate\Support\Carbon;
* @property bool $ignore_limits
* @property array<string, mixed>|null $report
* @property string|null $error_message
* @property string|null $error_details
* @property Carbon|null $started_at
* @property Carbon|null $finished_at
* @property string $organization_id
@@ -67,6 +68,7 @@ class Import extends Model
*/
protected $hidden = [
'credentials',
'error_details',
];
/**

View File

@@ -19,11 +19,14 @@ use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use LogicException;
use Throwable;
class ImportService
{
private const int ERROR_DETAILS_MAX_LENGTH = 50000;
/**
* Stores the import file and queues the import.
*
@@ -102,10 +105,12 @@ class ImportService
report($exception);
$import->status = ImportStatus::Failed;
$import->error_message = $exception->getMessage();
$import->error_details = $this->getErrorDetails($exception);
} catch (Throwable $exception) {
report($exception);
$import->status = ImportStatus::Failed;
$import->error_message = 'Unexpected error during import';
$import->error_details = $this->getErrorDetails($exception);
} finally {
$import->credentials = null;
$import->finished_at = Carbon::now();
@@ -125,6 +130,23 @@ class ImportService
$import->save();
}
/**
* Technical details of the exception and all previous exceptions for debugging in the admin panel.
*/
private function getErrorDetails(Throwable $exception): string
{
$parts = [];
$current = $exception;
while ($current !== null) {
$parts[] = $current::class.': '.$current->getMessage()."\n".
'at '.$current->getFile().':'.$current->getLine()."\n".
$current->getTraceAsString();
$current = $current->getPrevious();
}
return Str::limit(implode("\n\nCaused by: ", $parts), self::ERROR_DETAILS_MAX_LENGTH);
}
/**
* @throws ImportException
*/

View File

@@ -67,10 +67,10 @@ class ClockifyProjectsImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -214,10 +214,10 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -70,10 +70,10 @@ class GenericProjectsImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -178,10 +178,10 @@ class GenericTimeEntriesImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -42,10 +42,10 @@ class HarvestClientsImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -73,10 +73,10 @@ class HarvestProjectsImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -160,10 +160,10 @@ class HarvestTimeEntriesImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -333,7 +333,7 @@ class SolidtimeImporter extends DefaultImporter
throw $exception;
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
} finally {
$temporaryDirectory?->delete();
$temporaryDirectoryZip?->delete();

View File

@@ -205,7 +205,7 @@ class TogglDataImporter extends DefaultImporter
throw $exception;
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
} finally {
$temporaryDirectory?->delete();
$temporaryDirectoryZip?->delete();

View File

@@ -162,10 +162,10 @@ class TogglTimeEntriesImporter extends DefaultImporter
} catch (ImportException $exception) {
throw $exception;
} catch (CsvException $exception) {
throw new ImportException('Invalid CSV data');
throw new ImportException('Invalid CSV data', previous: $exception);
} catch (Exception $exception) {
report($exception);
throw new ImportException('Unknown error');
throw new ImportException('Unknown error', previous: $exception);
}
}

View File

@@ -35,6 +35,7 @@ class ImportFactory extends Factory
'ignore_limits' => false,
'report' => null,
'error_message' => null,
'error_details' => null,
'started_at' => null,
'finished_at' => null,
'organization_id' => Organization::factory(),

View File

@@ -30,7 +30,10 @@ return new class extends Migration
// Imports started by a super admin (admin panel) are not limited by the configured import limits
$table->boolean('ignore_limits')->default(false);
$table->jsonb('report')->nullable();
// Error message shown to the user
$table->text('error_message')->nullable();
// Technical error details (exception chain and stack trace), only visible in the admin panel
$table->text('error_details')->nullable();
$table->dateTime('started_at')->nullable();
$table->dateTime('finished_at')->nullable();
$table->uuid('organization_id');

View File

@@ -5,6 +5,8 @@ declare(strict_types=1);
namespace Tests\Unit\Filament\Resources;
use App\Filament\Resources\ImportResource;
use App\Filament\Resources\OrganizationResource;
use App\Filament\Resources\UserResource;
use App\Models\Import;
use App\Models\User;
use Illuminate\Support\Facades\Config;
@@ -57,4 +59,24 @@ class ImportResourceTest extends FilamentTestCase
// Assert
$response->assertSuccessful();
}
public function test_view_page_of_failed_import_shows_error_details_and_links_to_organization_and_user(): void
{
// Arrange
$import = Import::factory()->failed()->create([
'error_details' => 'RuntimeException: Not null violation',
]);
// Act
$response = Livewire::test(ImportResource\Pages\ViewImport::class, [
'record' => $import->getKey(),
]);
// Assert
$response->assertSuccessful();
$response->assertFormFieldExists('error_details');
$response->assertSchemaStateSet(['error_details' => 'RuntimeException: Not null violation']);
$response->assertSee(OrganizationResource::getUrl('view', ['record' => $import->organization_id]), false);
$response->assertSee(UserResource::getUrl('view', ['record' => $import->user_id]), false);
}
}

View File

@@ -208,9 +208,39 @@ class ImportServiceTest extends TestCase
$import->refresh();
$this->assertSame(ImportStatus::Failed, $import->status);
$this->assertSame('Unexpected error during import', $import->error_message);
$this->assertStringStartsWith('RuntimeException: Something went wrong', (string) $import->error_details);
$this->assertSame(0, TimeEntry::query()->count());
}
public function test_process_stores_previous_exception_in_error_details_if_importer_wraps_unknown_error(): void
{
// Arrange
Storage::fake(config('filesystems.private'));
Storage::disk(config('filesystems.private'))->put('import/test', 'data');
$import = Import::factory()->create([
'file_path' => 'import/test',
]);
$importer = $this->mock(ImporterContract::class, function (MockInterface $mock): void {
$mock->shouldReceive('init')->once();
$mock->shouldReceive('importData')
->once()
->andThrow(new ImportException('Unknown error', previous: new RuntimeException('Not null violation')));
});
$this->mock(ImporterProvider::class, function (MockInterface $mock) use ($importer): void {
$mock->shouldReceive('getImporter')->with('toggl_time_entries')->andReturn($importer);
});
// Act
app(ImportService::class)->process($import);
// Assert
$import->refresh();
$this->assertSame(ImportStatus::Failed, $import->status);
$this->assertSame('Unknown error', $import->error_message);
$this->assertStringStartsWith(ImportException::class.': Unknown error', (string) $import->error_details);
$this->assertStringContainsString('Caused by: RuntimeException: Not null violation', (string) $import->error_details);
}
public function test_process_fails_and_rolls_back_if_import_exceeds_record_limit(): void
{
// Arrange