laravel新建异常类

1.新建异常类 php artisan make:exception ApiException

<?php

namespace AppExceptions;

use Exception;
use Throwable;

class ApiException extends Exception
{
    public function __construct($message = "", $code = 400, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

    public function render()
    {
        return response()->json([
            'msg' => $this->message,
            'code' => $this->code,
        ], $this->code);
    }
}

2.方法中使用异常类

引入异常类
use AppExceptionsApiException;


方法中抛出异常
throw new ApiException('该商品不存在');

3.如果有使用Dingo,Dinggo会接管laravel的异常,render()方法不被执行,需要在服务提供者中屏蔽部分信息,找到appProvidersAppServiceProvider.php中的boot方法,添加屏蔽代码

public function boot()
{
    Schema::defaultStringLength(200);

    //有使用dinggo的话,添加如下代码屏蔽部分不需要显示内容
    app('api.exception')->register(function (Exception $exception) {
        $request = Request::capture();
        return app('AppExceptionsHandler')->render($request, $exception);
    });
}

4.新建的异常会被写进laravel的日志文件,不需要的可以在异常基类 appExceptionsHandler.php 中添加排除

<?php

namespace AppExceptions;

use IlluminateFoundationExceptionsHandler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * 添加不需要写进laravel日志的异常类
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        ApiException::class,
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }
}

可以手动写入

Log::error($this->message);

参考:六星教育-大神进阶班第一期-00.大神进阶第一期1.框架专题1-06-laravel项目实战10-自定义异常处理

原文地址:https://www.cnblogs.com/clubs/p/15313917.html