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

时间:2019-02-13 21:42:11

标签: laravel exception-handling

我创建了API,并实现了各种自定义异常。异常似乎可以对用户做出响应。因此,我的控制器方法可以返回响应,也可以引发自定义异常,这又将返回错误响应(见下文):

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)基类是否允许渲染响应。

1 个答案:

答案 0 :(得分:1)

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

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

我会做的:

  <div style={{ position: 'relative' }} id='outsideVideo' >
            <Video disableremoteplayback="true"
              id="videoId"
              onEnded={this.onVideoEnd}
              onPause={this.onVideoPause}
              width="100%"
              autoPlay={this.state.autoPlay}
              controls={['PlayPause', 'Seek', 'Time', 'Volume', 'Fullscreen']}
              poster={this.getInfo() ? this.getInfo().background : ''}
              ref='videoRef'
              style={{position:'relative'}}
              src={this.getLink() ? (this.getLink().jwplayer && this.getLink().jwplayer.length ? this.getLink().jwplayer[0].file : null) : null}>
            </Video>
            <div style={{  position: 'absolute', bottom: 40, right: 0, zIndex: 999 }} id='nextEpisodeLabel'>
              <label style={{ fontSize: '0.8rem', fontWeight: 600, color: 'white', padding: '5px 10px', margin: 5, backgroundColor: '#0487d6', position: 'absolute', right: 0, bottom: 0 }}>
                Next ep in 10 seconds
                  </label>
            </div>


          </div> 

然后创建一个类ng generate @angular/material:materialNav --name=main-nav --style=sass

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); } } ,以便laravel为您抛出异常