Example Usage of Error and Exception Handling in Laravel

  • 2021-11-01 23:56:29
  • OfStack

Preface

In this article, we'll explore one of the most important and least discussed features of the Laravel Web framework-exception handling. Laravel comes with a built-in exception handler that makes it easy to report and present exceptions in a friendly manner.

Laravel comes with error and exception handling, while App\ Exceptions\ Handler is responsible for reporting exceptions and how to return content, as well as handling unlogged.

App\ Exceptions\ Handler is located in app\ Exceptions\ Handler. php, and the properties and usage of this class are described below. Ok, I don't have much to say. Let's take a look at the detailed introduction

Ignore exceptions

You can define ignored exception class names in $dontReport:


protected $dontReport = [
 \Illuminate\Auth\AuthenticationException::class,
 \Illuminate\Auth\Access\AuthorizationException::class,
 \Symfony\Component\HttpKernel\Exception\HttpException::class,
 \Illuminate\Database\Eloquent\ModelNotFoundException::class,
 \Illuminate\Validation\ValidationException::class,
];

These exceptions do not pass through the report method.

Several important methods

This paper mainly introduces the usage of these three methods, report, render and unauthenticated.

report method

The report method can be used to log, and different log levels and log contents can be customized according to different exception types (including custom exception types), such as ClientException and ConnectException.


if ($exception instanceof ABCException) {
 Log::emergency('ABC Anomaly ', $context);
} else if ($exception instanceof HeheException) {
 Log::info('Hehe Anomaly ', $context);
}

The report method has no return value and should not break the program here.

render method

The render method can return different data according to different exception types. Such as:


if (get_class($exception) == 'Exception' || $exception instanceof NotAllowedException) {
 return response()->json(['message' => $exception->getMessage()], 400);
} elseif ( $exception instanceof ValidationException) {
 return response()->json(['message' => ' Verification failure ', 'errors'=> $exception->validator->errors()], 400);
}

unauthenticated

When visiting the page that needs login status, the user will enter this method for processing if he is not logged in. Give an example:


protected function unauthenticated($request, AuthenticationException $exception)
{
 if ($request->expectsJson()) {
  return response()->json(['error' => 'Unauthenticated.'], 401);
 }
 
 // If the background page is not authenticated , Jump to Background Landing Page 
 $guard = $exception->guards();
 if (in_array('admin', $guard)) {
  return redirect()->guest('/admin/login');
 }
 
 return redirect()->guest('login');
}

If json is returned, the format is returned.

By default, it returns to the foreground login page. If you are visiting the background page without logging in, you will jump to the background login page.

Official documents

Laravel 5.6

https://laravel-china.org/docs/laravel/5.6/errors/1373

Summarize


Related articles: