1. Go to this page and download the library: Download jnewer/exception-handler library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
use Illuminate\Validation\ValidationException;
use Jnewer\ExceptionHandler\Exception\BaseException;
use Jnewer\ExceptionHandler\BaseExceptionHandler;
use Jnewer\ExceptionHandler\ValidationExceptionHandler;
return [
'enable' => true,
'exception' => [
// 这里配置异常类和对应的处理类
'handlers' => [
ValidationException::class => ValidationExceptionHandler::class,
BaseException::class => BaseExceptionHandler::class
],
'dont_report' => [
BusinessException::class,
BaseException::class,
ValidationException::class,
]
]
];
use support\Request;
use support\Response;
use Jnewer\ExceptionHandler\Exception\NotFoundHttpException;
class UserController{
public function view($id): Response
{
$user = User::find($id);
if (is_null($user)) {
throw new NotFoundHttpException('用户不存在');
}
}
}
namespace support\exception;
use Jnewer\ExceptionHandler\Exception\BaseException;
class InvalidArgumentException extends BaseException
{
}
use support\Request;
use support\Response;
use support\exception\InvalidArgumentException;
class UserController{
public function create(Request $request): Response
{
if (!$request->post('name')) {
throw new InvalidArgumentException('参数有误');
}
}
}
namespace support\exception;
use support\exception\Handler;
use Illuminate\Validation\ValidationException;
use Throwable;
use function json_encode;
class InvalidArgumentExceptionHandler extends Handler
{
public function render(Request $request, Throwable $exception): Response
{
$message = $exception->getMessage();
$statusCode = $exception->statusCode ?? 500;
if (!$request->expectsJson()) {
return new Response($statusCode, [], $message);
}
$jsonMessage = ['code' => $exception->code ?: $exception->statusCode, 'message' => $message, 'success' => false, 'data' => []];
return new Response(
$statusCode,
['Content-Type' => 'application/json'],
json_encode($jsonMessage, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
);
}
}