Laravel异常处理

Laravel异常处理

标签(空格分隔): php

自定义异常类

<?php
namespace App\Exceptions;

use Throwable;
use Exception;

class ApiException extends Exception
{

    public function __construct($code, \Throwable $previous = null)
    {
        parent::__construct(config('jsoncode.code')[(int) $code], $code, $previous);
    }

    /**
     * 报告异常
     *
     * @return void
     */
    public function report()
    {
        //
    }

    /**
     * 转换异常为 HTTP 响应
     *
     * @param  \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function render($request)
    {
         return response()->json([
             'code' => $this->getCode(),
             'message' => $this->getMessage(),
        ]);
    }
}

修改app/exceptions/Handler 类中的render方法

getenv() 获取env配置信息

抛出异常

throw new ApiException(500);

猜你喜欢

转载自www.cnblogs.com/yanweifeng/p/10955490.html