如何在Laravel中将异常委托给全局异常?

如何在Laravel中将异常委托给全局异常?,laravel,laravel-5,Laravel,Laravel 5,控制器Laravel中有典型代码: public function create(CreateInvoiceRequest $request) { try { $invoice = Invoice::create(['']); return response()->json($model); } catch (\Exception $e) { return \Respon

控制器Laravel中有典型代码:

public function create(CreateInvoiceRequest $request)
    {

        try {

            $invoice = Invoice::create(['']);

            return response()->json($model);

        } catch (\Exception $e) {
            return \Response::json(["errors" => $e->getMessage()], 400);
        }
    }
在异常情况下,我捕捉到它并显示消息,如何在全局异常Laravel中删除(移动)它?我需要这样做吗

try { } } catch (\Exception $e) { throw new Exception($e); }

Laravel有一个很好的解决方案。在中,我们被告知在
App\Exceptions\Handler
中处理此类异常

下面是一个非常简单的例子:

// Your controller.

try {

    $invoice = Invoice::create(['']);

    return response()->json($model);

} catch (\Exception $e) {
    throw new CustomException('Invoice creation failed.');
}

// app\Exceptions\Handler.php

public function render($request, Exception $exception)
{
    if ($exception instanceof CustomException) {
        return response()->view('errors.custom', [], 500);
    }

    return parent::render($request, $exception);
}
我试图找出
create
是否会引发特定的异常。不幸的是,我没能这么快找到答案。如果是这种情况,您可以删除
try-catch
,只需在
render
方法中侦听此特定异常

更新

(未测试)

此外,还可以覆盖
save
方法,以避免使用
try
catch
来包装(所有)数据库写入方法调用

我们需要一个
BaseModel
类:

<?php

namespace App\Models;

use App\Exceptions\ModelSaveException;
use Illuminate\Database\Eloquent\Model as EloquentModel;

class Model extends EloquentModel
{
    /**
     * Save the model to the database.
     *
     * @param  array  $options
     * @return bool
     * @throws \App\Exceptions\ModelSaveException
     */
    public function save(array $options = [])
    {
        try {
            return parent::save($options);
        } catch(\Exception $e) {
            throw new ModelSaveException($this);
        }
    }
}
另外,我们可以检查我们的模型是否是通过使用
exists
属性创建的

<?php

namespace App\Exceptions;

class ModelSaveException extends \Exception
{
    /**
     * ModelSaveException constructor.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
     public function __construct($model)
     {
        if ($model->exists) {
            parent::__construct('Failed updating model.');
        } else {
            parent::__construct('Failed creating model.');
        }
     }
}


可以创建自定义的可渲染异常

try {
    // Your code...
} catch (\Exception $e) {
    throw new \App\Exceptions\CustomException('Your message');
}
您可以直接在自定义异常上定义报告和呈现方法,而不是在异常处理程序的报告和呈现方法中进行类型检查异常。当这些方法存在时,框架将自动调用它们:

有关更多信息:

use App\Models\Model;

class Invoice extends Model
try {
    // Your code...
} catch (\Exception $e) {
    throw new \App\Exceptions\CustomException('Your message');
}
/**
 * Report the exception.
 *
 * @return void
 */
public function report()
{
    //
}

/**
 * Render the exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request
 * @return \Illuminate\Http\Response
 */
public function render($request)
{
    return response(...);
}