Customize how your exceptions are rendered

You can customize how your exceptions are rendered by adding a 'render' method to your exception.

For example, this allows you to return JSON instead of a Blade view when the request expects JSON.

abstract class BaseException extends Exception
{
public function render(Request $request)
{
if ($request->expectsJson()) {
return response()->json([
'meta' => [
'valid' => false,
'status' => static::ID,
'message' => $this->getMessage(),
],
], $this->getCode());
}
 
return response()->view('errors.' . $this->getCode(), ['exception' => $this], $this->getCode());
}
}
class LicenseExpiredException extends BaseException
{
public const ID = 'EXPIRED';
protected $code = 401;
protected $message = 'Given license has expired.'
}

Tip given by @Philo01

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 68 courses (1188 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses