1、首先我们在app/Exceptions
目录新建一个ExceptionHandler.php
继承自同目录下的Handler.php
代码如下
在render方法里,我们根据.env文件中的APP_DEBUG来判断,如果是调试模式,我们还是按照默认方式来渲染错误,如果是非调试模式,我们就返回JSON格式的信息
<?php
namespace App\Exceptions;
class ExceptionHandler extends Handler
{
public function render($request, \Throwable $exception)
{
if (env('APP_DEBUG')) {
return parent::render($request, $exception);
}
return response()->json([
'code' => $exception->getCode(),
'msg' => $exception->getMessage()
]);
}
}
2、然后我们在bootstrap/app.php
中,使用我们自定义的异常处理类ExceptionHandler
替换掉默认的Handler类
//改为我们自定义的ExceptionHandler类
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\ExceptionHandler::class
);