DEV Community

Recca Tsai
Recca Tsai

Posted on Originally published at recca0120.github.io

Throw Laravel ValidationException Manually for API Errors

Originally published at recca0120.github.io

Scenario

When calling an external API and receiving an error response, I want to wrap the error as a ValidationException so the frontend can display it the same way as form validation errors.

Solution

use Illuminate\Validation\ValidationException;

try {
    // call external API
} catch (Exception $e) {
    throw ValidationException::withMessages([
        'field' => [$e->getMessage()],
    ]);
}
Enter fullscreen mode Exit fullscreen mode

withMessages() accepts the same format as Validator errors — the key is the field name and the value is an array of error messages. The JSON structure the frontend receives will be identical to a regular validation failure.

Top comments (0)