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.

1abstract class BaseException extends Exception
2{
3 public function render(Request $request)
4 {
5 if ($request->expectsJson()) {
6 return response()->json([
7 'meta' => [
8 'valid' => false,
9 'status' => static::ID,
10 'message' => $this->getMessage(),
11 ],
12 ], $this->getCode());
13 }
14 
15 return response()->view('errors.' . $this->getCode(), ['exception' => $this], $this->getCode());
16 }
17}
1class LicenseExpiredException extends BaseException
2{
3 public const ID = 'EXPIRED';
4 protected $code = 401;
5 protected $message = 'Given license has expired.'
6}

Tip given by @Philo01

Like our articles?

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