hcan Bir exception'ı API response olarak kullanmak için şöyle yapabilirsiniz mesela:
app/Exceptions/CustomException.php
interface CustomException
{
}
app/Exceptions/LoginException.php
class LoginException extends Exception implements CustomException
{
}
app/Exceptions/Handler.php::$dontReport[]:
protected $dontReport = [
CustomException::class,
];
app/Exceptions/Handler.php::register():
$this->renderable(function (CustomException $e, $request) {
if ($request->expectsJson()) {
return response()->json([
'message' => $e->getMessage(),
], $e->getCode() ?? 400);
}
});
Böylece siz throw new LoginException(__('Kullanıcı adı ya da şifre hatalı')) yaptığınızda eğer exception json isteyen bir Request karşılığında Response olarak dönerse otomatik olarak json response'a dönüşür. Bu şekilde LoginException uygulama içinde her yerde kullanılabilir. İç işlerinizde try...catch ile yakalarsınız, API isteklerinde otomatik Response olarak döner.