Laravel中的App\Exceptions\Handler 类负责记录应用程序触发的所有异常,这在我们开发过程中十分方便,总是try…catch使代码太过繁琐且可读性大大降低,那么怎么使用它处理异常为json
呢?
我们可以新建一个class,用来处理异常返回。
<?php /** * Author: sai * Date: 2020/1/15 * Time: 14:31 */
namespace App\Exceptions;
class ApiException extends \Exception { const ERROR_CODE = 1001; const ERROR_MSG = 'ApiException';
private $data = [];
/** * BusinessException constructor. * * @param string $message * @param string $code * @param array $data */ public function __construct(string $message, string $code, $data = []) { $this->code = $code ? : self::ERROR_CODE; $this->message = $message ? : self::ERROR_MSG; $this->data = $data; }
/** * @return array */ public function getData() { return $this->data; }
/** * 异常输出 */ public function render($request) { return response()->json([ 'data' => $this->getData(), 'code' => $this->getCode(), 'messgae' => $this->getMessage(), ], 200); } }
|
然后我们在Handler加入,加入$dontReport
,便不会使用自带的错误处理,而使用自定义的处理。
<?php
namespace App\Exceptions;
use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler { /** * 一些不需管或不需要抛出的异常 */ protected $dontReport = [ ApiException::class, ];
... }
|
我们测试一下:
<?php
namespace App\Http\Controllers;
use App\Exceptions\ApiException; use Illuminate\Http\Request;
class HomeController extends Controller { public function index(Request $request) { throw new ApiException('error', 10001, ['oh' => 'no']); return 1; } }
|
查看输出:

测试ok,我们可以愉快的使用啦。当然,其他形式的错误输出可以自行扩展。