{Laravel} How to Handle Translatable Exceptions
Hi, today I want to share a way to have exceptions with a translatable message. In this post, I'm assuming that you have a comprehensive knowledge of the Laravel framework and use the latest PHP version, which at the time of writing is 8.1.
Let's create a new exception with the following command:
php artisan make:exception User/UserCouldNotBeCreated
We then create an interface that all the custom exceptions will need to conform with:
namespace App\Interfaces\Exceptions;
interface ExceptionTranslatable
{
public function getTranslatedMessage(): string;
}
We then create a new trait that will help us fulfill a common scenario
namespace App\Traits\Exceptions;
use Illuminate\Http\Response;
trait HasExceptionTranslatedMessage
{
public function getTranslatedMessage(): string
{
return trans('exceptions.' . __CLASS__);
}
public function render(): Response
{
return response([
'error' => $this->getTranslatedMessage(),
], $this->getErrorCode());
}
protected function getErrorCode(): int
{
return Response::HTTP_INTERNAL_SERVER_ERROR;
}
}
I decided to store my translations like so:
// lang/en/exceptions.php
use App\Exceptions\User\UserCouldNotBeCreated;
use App\Exceptions\User\UserCouldNotBeDeleted;
use App\Exceptions\User\UserCouldNotBeUpdated;
return [
UserCouldNotBeCreated::class => 'The user could not be created. Please contact support.',
UserCouldNotBeUpdated::class => 'The user could not be updated. Please contact support.',
UserCouldNotBeDeleted::class => 'The user could not be deleted. Please contact support.',
];
We then use the newly created trait and interface in the custom exception:
namespace App\Exceptions\User;
use App\Interfaces\Exceptions\ExceptionTranslatable;
use App\Traits\Exceptions\HasExceptionTranslatedMessage;
use Exception;
class UserCouldNotBeCreated extends Exception implements ExceptionTranslatable
{
use HasExceptionTranslatedMessage;
}
You can now use it by simply using
throw new UserCouldNotBeDeleted
If you have any questions, please leave a comment below.