关于laravel:Laravel-统一错误处理为-JSON

5次阅读

共计 1303 个字符,预计需要花费 4 分钟才能阅读完成。

Laravel 中的 AppExceptionsHandler 类负责记录应用程序触发的所有异样,这在咱们开发过程中非常不便,总是 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,咱们能够欢快的应用啦。当然,其余模式的谬误输入能够自行扩大。

正文完
 0