DEV Community

Debajyoti Das
Debajyoti Das

Posted on

Laravel error handling

Just a post on Exception handling using Laravel, the following code is for catching known exceptions:


    public function set_quote(Request $request)
    {

        // Validate input
        $this->rules = [
            'id' => '',
            'author' => 'required',
            'quote' => 'required',
        ];
        $validator = Validator::make($request->all(), $this->rules);

        if($validator->fails())
            return response()->json(['code'=>400, 'message'=>$validator->errors()->first()], 200);
        try{

            $resp = Quote::updateOrCreate(['id' => $request->id], $request->all());
            $this->data['response'] = $resp;
            if($resp->wasRecentlyCreated == true)
                return response()->json(['code'=>200, 'message' => 'Created Successfully', 'data'=>$this->data], 200);       
            elseif($resp->wasRecentlyCreated == false)
                return response()->json(['code'=>200, 'message' => 'Updated Successfully', 'data'=>$this->data], 200);   
        }
        catch(\Illuminate\Database\QueryException $e)
        {
            $er_msg = 'Data truncated as data too long';   
            return response()->json(['code'=>400, 'message' => $er_msg, 'data'=>[]], 200);
        }
        catch(Exception $e)
        {
            //echo get_class($e); //To get the exception class name
            $er_msg = $e->getMessage();   
            return response()->json(['code'=>400, 'message' => $er_msg, 'data'=>[]], 200);
        }    
        /*finally
        {
            return response()->json(['code'=>400, 'message' => $er_msg, 'data'=>[]], 200);   
        }*/

    }
Enter fullscreen mode Exit fullscreen mode

N.B: For namespacing, you need to first \ if the class is not included as a use statement.

Top comments (0)