异常应处理返回的错误响应

问题描述 投票:0回答:1

我创建了API并实现了各种自定义异常。看起来Exceptions可以呈现对用户的响应。所以我的控制器方法可以返回响应,也可以抛出自定义异常,然后返回错误响应(见下文):

public function destroy($id)
{
    try {
        $myModel = MyModel::find($id);
        if ($myModel !== null) {
            $service = new ModelService($sequence);
            if($service->destroyModel())
                return $this->deleteSuccess($sequence);
        } else {
            throw new Exception('Could not find Model.', 404);
        }
    }
    catch(Exception $e)
    {
        throw new DeleteModelException($e->getMessage(), $e->getCode(), $e);
    }
    //this path is never reached, function technically has path that doesn't return
}

从技术上讲,我有一条不返回任何东西的路径,但是DeleteModelException处理其余部分。

这是一个好的做法还是我应该只在控制器中保留错误响应?不知道为什么基本的ExceptionIlluminate\Foundation\Exception)类允许渲染响应,如果不是为了这个。

laravel exception-handling
1个回答
1
投票

我强烈建议抛出自定义和描述性异常的做法,让异常的render方法为您返回响应。

当项目变得更大并且您使用应用程序观察工具(例如sentry)跟踪异常时,这些异常将有助于了解项目中发生的事情。

我会做 :

public function something(){

    try{
        // actions
    }
    catch(\Exception $e){
        throw new \SomethingFailedExeption('Faild to do something');
    }
}

然后创建一个类App\Exceptions\SomethingFailedExeption

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Http\Request;

class SomethingFailedExeption extends Exception
{
    /**
     * Render the exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function render(Request $request)
    {
        return response()->json([
            'message' => $this->getMessage(),
            'somefield' -> $request->somefield
        ], 500);
    }
}

我也会推荐FindorFail(而不是Find(),以便laravel为你抛出异常

© www.soinside.com 2019 - 2024. All rights reserved.